#!/bin/bash

set -e

source /usr/share/mediawiki-shell/common
source /usr/share/mediawiki-shell/wiki-config

check_vars_exist "WIKI_INDEX" "wiki_article_to_fetch" "wiki_fetch_to_file"

true "$0: INFO: Fetching '${WIKI_INDEX}' '$wiki_article_to_fetch' '$wiki_fetch_to_file'..."

if test -d "$wiki_fetch_to_file" ; then
   echo "$0: ERRROR: wiki_fetch_to_file '$wiki_fetch_to_file' is a folder!" >&2
   exit 1
fi

rm -f "$wiki_fetch_to_file"
touch "$wiki_fetch_to_file"
test -w "$wiki_fetch_to_file"

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

curl_run \
   $curl_opts \
   --header "Accept-Language: en-GB" \
   --header "Expect:" \
   --output "$wiki_fetch_to_file" \
   "${WIKI_INDEX}?title=$wiki_article_to_fetch&action=raw"

test -r "$wiki_fetch_to_file"

true "$0: INFO: Fetch success."
