#!/bin/bash

## Copyright (C) 2025 - 2025 ENCRYPTED SUPPORT LLC <adrelanos@whonix.org>
## See the file COPYING for copying conditions.

set -o errexit
set -o nounset
set -o errtrace
set -o pipefail

# shellcheck source=../share/mediawiki-shell/common
source /usr/share/mediawiki-shell/common

log info "START"

usage() {
  printf '%s\n' "Usage: ${0##*/} [OPTIONS] WIKI WIKI_TARGET PAGE [OUTPUT]
Options:
  --edit-msg=X     Summary to specify for edit
Defaults:
  OUTPUT=todo
Example:
  ${0##*/} 'https://www.kicksecure.com/w' 'https://www.whonix.org/w' About
  ${0##*/} 'https://www.kicksecure.com/w' 'https://www.whonix.org/w' About $TMPFOLDER/About" >&2
  exit 1
}

# shellcheck source=/usr/libexec/helper-scripts/parse_opt.sh
source /usr/libexec/helper-scripts/parse_opt.sh

edit_msg=""

while true; do
  [[ "${1-}" =~ ^- ]] || break
  begin_optparse "${1-}" "${2-}" || break
  true "${opt-}" "${arg-}" "${opt_orig-}"
  case "${opt}" in
    edit-msg) get_arg; edit_msg="${arg}";;
    h|help) usage;;
    --|"") break;;
    *) die 2 "Invalid option: '${opt_orig}'"
  esac
  shift "${shift_n:-1}"
done

if [[ -z "${3-}" ]]; then
  usage
fi

WIKI_URL="$1"
wiki_url_target="$2"
page_title="$3"
page_title_local="${4-}"
if [ -z "$page_title_local" ]; then
  log info "default output_file: yes"
  page_title_local="$(set_backup_page_item "$page_title")"
  output_file="$TMPFOLDER/$page_title_local"
else
  log info "default output_file: no"
  output_file="$page_title_local"
fi

check_vars_exist wiki_url_target page_title

# shellcheck source=../share/mediawiki-shell/wiki-config
source /usr/share/mediawiki-shell/wiki-config

log info "WIKI_URL             : $WIKI_URL"
log info "WIKI_API             : $WIKI_API"
log info "wiki_url_target      : $wiki_url_target"
log info "page_title           : $page_title"
log info "page_title_local     : $page_title_local"
log info "output_file          : $output_file"

#mw-login-test "$WIKI_URL"

log info "Fetching page '$WIKI_URL' '$page_title' '$output_file'..."
mw-fetch "$WIKI_URL" "$page_title" "$output_file"
log info "Fetch page success."

## 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.
mw-page-pending-check "$WIKI_URL" "$page_title"

log info "Editing page... '$wiki_url_target' '$output_file' '$page_title'"

if [ -n "$edit_msg" ]; then
  mw-edit "$wiki_url_target" "$output_file" "$page_title" "$edit_msg"
else
  mw-edit "$wiki_url_target" "$output_file" "$page_title"
fi

log info "Edit page success."
