#!/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
export LC_ALL=C
## style-ok: no-tmp-hardcode -- /tmp appears only in usage() example paths.

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

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

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

WIKI_URL="$1"
page_title="$2"
new_file="$3"

check_vars_exist page_title new_file

## Defense-in-depth: check page_title for malicious unicode before
## interpolating it into API URLs.
printf '%s\n' "${page_title}" | unicode-show

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

log info "Fetching '${WIKI_INDEX}' '${page_title}' '${new_file}'..."

if test -d "${new_file}"; then
  die 1 "new_file '${new_file}' is a folder!"
fi

safe-rm -f -- "${new_file}"
touch -- "${new_file}"
test -w "${new_file}"

# curl_run \
#    "${curl_opts[@]}" \
#    --cookie "$cookie_jar" \
#    --cookie-jar "$cookie_jar" \
#    --header "Accept-Language: en-GB" \
#    --header "Expect:" \
#    --data-urlencode "title=$page_title" \
#    --request "POST" "${WIKI_INDEX}?action=raw"

curl_run \
  "${curl_opts[@]}" \
  --header "Accept-Language: en-GB" \
  --header "Expect:" \
  --output "${new_file}" \
  --get \
  --data-urlencode "title=${page_title}" \
  --data-urlencode "action=raw" \
  "${WIKI_INDEX}"

test -r "${new_file}"

log info "Fetch success."
