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

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

# 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" \
  "${WIKI_INDEX}?title=$page_title&action=raw"

test -r "$new_file"

log info "Fetch success."
