#!/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
shopt -s inherit_errexit
shopt -s shift_verbose

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

log info "START"

usage() {
  printf '%s\n' "Usage: ${0##*/} [OPTIONS] WIKI
Options:
  --continue-from=N|TITLE    Continue from page index (N) or title (case-insensitive)
  --keep-going               Continue past per-item failures (record them, exit non-zero)
  --retry                    Skip items already recorded done; retry the rest
  --reset                    Clear any prior state before starting
  --state-file=PATH          Override the state-file location (default: under TMPFOLDER)
Example:
  ${0##*/} https://www.kicksecure.com/w
  ${0##*/} --continue-from=500 https://www.kicksecure.com/w
  ${0##*/} --continue-from='My_Page' https://www.kicksecure.com/w" >&2
  exit 1
}

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

continue_from=""
keep_going_arg=""
retry_arg=""
reset_arg=""
state_file_arg=""

while true; do
  [[ "${1-}" =~ ^- ]] || break
  begin_optparse "${1:-}" "${2:-}" || break
  true "${opt-}" "${arg-}" "${opt_orig-}"
  case "${opt}" in
    continue-from)
      get_arg
      continue_from="${arg}"
      ;;
    keep-going)
      keep_going_arg="--keep-going"
      ;;
    retry)
      retry_arg="--retry"
      ;;
    reset)
      reset_arg="--reset"
      ;;
    state-file)
      get_arg
      state_file_arg="--state-file=${arg}"
      ;;
    h|help)
      usage
      ;;
    --|"")
      break
      ;;
    *)
      die 2 "Invalid option: '${opt_orig}'"
      ;;
  esac
  shift "${shift_n:-1}"
done

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

WIKI_URL="$1"

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

log info "TMPFOLDER    : $TMPFOLDER"
log info "WIKI_URL     : $WIKI_URL"
log info "WIKI_API     : $WIKI_API"
log info "continue_from: ${continue_from-}"

mw_process_args=()
if [ -n "$continue_from" ]; then
  mw_process_args+=("--continue-from=$continue_from")
fi
for forwarded_arg in "$keep_going_arg" "$retry_arg" "$reset_arg" "$state_file_arg"; do
  if [ -n "$forwarded_arg" ]; then
    mw_process_args+=("$forwarded_arg")
  fi
done

mw-process-all-pages "${mw_process_args[@]}" "${WIKI_URL}" 'mw-patch-modify-wiki-page' "$TMPFOLDER"
