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

# shellcheck disable=SC2317
exit_handler() {
  [[ -v retry_counter ]] || retry_counter=0
  if (( retry_counter > 1 )); then
    log notice "success after attempt $retry_counter"
  fi
}

trap exit_handler EXIT

usage() {
  printf '%s\n' "Usage: ${0##*/} WIKI PAGE OUTPUT
Example:
  ${0##*/} 'https://www.kicksecure.com/w' Some_Article /tmp/a" >&2
  exit 1
}

if [[ -z "${3-}" || "${1-}" =~ (-h|--help) ]]; then
  usage
fi

wiki_url="$1"
page="$2"
output="$3"

check_vars_exist page output

output_dir="$(dirname "${output}")"
log info "output_dir: $output_dir"

mkdir -p -- "$output_dir"
if ! test -d "$output_dir"; then
  die 1 "output_dir '$output_dir' does not exist! Run?: mkdir --parents -- '$output_dir'"
fi

if ! test -w "$output_dir"; then
  die 1 "output_dir '$output_dir' unwritable! Run?: chown --recursive -- '$USER:$USER' '$output_dir'"
fi

for retry_counter in {1..5}; do
  if mw-fetch "$wiki_url" "$page" "$output"; then
    exit 0
  fi
  sleep 5
done

## Failed even after retry attempts. Therefore exit non-zero.
exit 1
