#!/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=100 '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=""

# shellcheck disable=SC2034  # KEEP_GOING/RETRY/STATE_RESET/STATE_FILE set here, read by common's state_* helpers
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="true"
      ;;
    retry)
      RETRY="true"
      ;;
    reset)
      STATE_RESET="true"
      ;;
    state-file)
      get_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

## TODO: abolish need for this and fetch all name spaces instead by default.
## Namespace 500 (Moved:) is not reviewable.
## Namespace 500 (Widget:) is not reviewable.
#export wiki_namespace_list_extra="500 274"

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

state_setup "$WIKI_URL"

login_function() {
  log info "Logging in..."
  mw-login-test "$WIKI_URL"
  log info "Login ok."
}

approve_page() {
  approve_page_exit_code=0
  mw-flagged-revisions-approve-page "$WIKI_URL" "$page_to_approve" || approve_page_exit_code="$?"
}

login_function

allpages_file="${TMPFOLDER}/allpages.txt"
safe-rm -f -- "$allpages_file"

mw-all-pages "$WIKI_URL" unreviewedpages "$allpages_file"

test -r "$allpages_file"
unicode-show "$allpages_file"
counter_total="$(awk 'END {print NR}' "$allpages_file")"

# shellcheck disable=SC2034  # mutated by should_start_processing via nameref
continue_state="no"
counter_currently=0
while IFS=$'\n' read -r item_from_all_pages; do
  (( counter_currently++ )) || true
  ## Raw page name - no filesystem encoding. The API handles spaces/underscores
  ## and curl_run handles URL encoding.
  page_to_approve="$item_from_all_pages"

  if ! should_start_processing "$counter_currently" "$item_from_all_pages" "$continue_from" continue_state; then
    log info "skip | $counter_currently / $counter_total | $item_from_all_pages"
    continue
  fi

  if state_should_skip "$item_from_all_pages"; then
    log info "retry-skip | $counter_currently / $counter_total | already done | $item_from_all_pages"
    continue
  fi

  log info "$counter_currently / $counter_total | $item_from_all_pages"
  printf '%s\n' "mw-flagged-revisions-approve-page '$WIKI_URL' '$page_to_approve'"
  approve_page
  if [ "$approve_page_exit_code" = "0" ]; then
    log info "Success at first attempt, ok."
    state_record_done "$page_to_approve"
    continue
  elif [ "$approve_page_exit_code" = "254" ]; then
    log info "Got exit code 254. Login probably expired."
    login_function
    log info "Try again..."
    approve_page
  fi

  if [ "$approve_page_exit_code" = "0" ]; then
    log info "Success after second attempt, ok."
    state_record_done "$page_to_approve"
  else
    state_record_fail "$page_to_approve" "approve rc=$approve_page_exit_code"
  fi
done <"$allpages_file"

state_finish
if [ "$state_fail_count" = "0" ]; then
  log info "Success."
else
  log warn "$state_fail_count error(s) detected."
  if state_enabled; then
    exit 2
  fi
fi
