#!/bin/bash

echo "$0: START"

set -e

source /usr/share/mediawiki-shell/common

## example:
#SOURCE_WIKI_URL='https://www.kicksecure.com/w' DESTINATION_WIKI_URL='https://www.whonix.org/w' wiki_remote_file_name="File:Ubuntu_software_icon.png" mw-copy-wiki-file

wiki_remote_file_title="$(echo "$wiki_remote_file_name" | str_replace "File:" "")"

[[ -v wiki_remote_file_save_to_path ]] || wiki_remote_file_save_to_path="$TMPFOLDER/wiki_remote_file_title"

[[ -v SOURCE_WIKI_URL ]] || missing_variable SOURCE_WIKI_URL
[[ -v DESTINATION_WIKI_URL ]] || missing_variable DESTINATION_WIKI_URL

[[ -v wiki_source_api ]] || wiki_source_api="${SOURCE_WIKI_URL}/api.php"

# WIKI_URL="$DESTINATION_WIKI_URL" \
#    mw-logout
# WIKI_URL="$DESTINATION_WIKI_URL" \
#    mw-login

check_vars_exist wiki_remote_file_name wiki_remote_file_save_to_path

echo "$0: INFO: Downloading file '$wiki_remote_file_name' '$wiki_remote_file_save_to_path'..."

WIKI_URL="$SOURCE_WIKI_URL" wiki_remote_file_name="$wiki_remote_file_name" wiki_remote_file_save_to_path="$wiki_remote_file_save_to_path" mw-file-download

echo "$0: INFO: Download file success."

echo "$0: INFO: Checking for pending changes for file..."
echo "$0: INFO: wiki_source_api: $wiki_source_api"

## time-of-check to time-of-use TOCTOU
## Check for pending edits only after page was fetched.
## Checking for pending edits before fetching page would leave room for
## making a pending edit after the page has been fetched.
## This ensures that the fetched edit was not pending, i.e. confirmed.
page_pending_status_json=$(\
   $curl \
      $curl_opts \
      "${wiki_source_api}?format=json&action=query&prop=info%7Cflagged&titles=$wiki_remote_file_name"
)

if echo "$page_pending_status_json" | jq | grep -q pending_since ; then
   echo "$0: WARNING: '$SOURCE_WIKI_URL' '$wiki_remote_file_name' has PENDING EDITS!"
   exit 10
fi

echo "$0: INFO: No pending edits for file, ok."

echo "$0: INFO: Uploading file... '$DESTINATION_WIKI_URL' '$wiki_remote_file_name' '$wiki_remote_file_save_to_path'"

WIKI_URL="$DESTINATION_WIKI_URL" \
wiki_remote_upload_file_title="$wiki_remote_file_title" \
wiki_remote_file_name="$wiki_remote_file_name" \
wiki_upload_file_path="$wiki_remote_file_save_to_path" \
mw-file-upload

echo "$0: INFO: Upload file success."
