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

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

pass_file=""

exit_handler_login() {
  local exit_code="$?"
  if [ -n "${pass_file-}" ]; then
    safe-rm -f -- "${pass_file}"
  fi
  exit_handler "${exit_code}"
}

trap exit_handler_login EXIT

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

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

WIKI_URL="$1"

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

log info "Logging into '${WIKI_API}' as '${WIKI_API_USER_NAME}'... Requesting Login token..."
safe-rm -f -- "${TMPFOLDER}"/login-{token,result}.json
curl_run \
  "${curl_opts[@]}" \
  --cookie "${cookie_jar}" \
  --cookie-jar "${cookie_jar}" \
  --header "Content-Type: application/json" \
  --header "Accept-Language: en-GB" \
  --output "${TMPFOLDER}/login-token.json" \
  --request "POST" \
  "${WIKI_API}?action=query&meta=tokens&type=login&format=json"
log info "Login Token received."
login_token="$(jq --raw-output '.query.tokens.logintoken' -- "${TMPFOLDER}/login-token.json")"

## Write password to a temp file so it does not appear in /proc/PID/cmdline.
## The umask (set in 'common') ensures the file is created with mode 0600.
pass_file="$(mktemp -t mw-login-pass.XXXXXXXX)" || die 1 "Failed to create temporary password file!"
printf '%s' "${WIKI_API_USER_PASS}" | sponge -- "${pass_file}"

curl_run \
  "${curl_opts[@]}" \
  --cookie "${cookie_jar}" \
  --cookie-jar "${cookie_jar}" \
  --header "Accept-Language: en-GB" \
  --data-urlencode "lgname=${WIKI_API_USER_NAME}" \
  --data-urlencode "lgpassword@${pass_file}" \
  --data-urlencode "lgdomain=${USERDOMAIN}" \
  --data-urlencode "lgtoken=${login_token}" \
  --output "${TMPFOLDER}/login-result.json" \
  --request "POST" \
  "${WIKI_API}?action=login&format=json"

safe-rm -f -- "${pass_file}"

## XXX:
## If already logged in:
## "login": {
## "result": "Aborted",
## "reason": "Cannot log in when using MediaWiki\\Session\\BotPasswordSessionProvider sessions."

result="$(jq --raw-output '.login.result' -- "${TMPFOLDER}/login-result.json")"

if [ "${result}" = "Success" ]; then
  log info "Successfully logged in as '${WIKI_API_USER_NAME}'."
  exit 0
fi

## FIXME: Sanitizing JSON before handing to jq is prohibited, see Bash
## style guide rule R-140. Sanitize after parsing with jq.
reason="$(jq -r ".login.reason" < <(stcat "${TMPFOLDER}/login-result.json"))"
die 1 "Login failed to '${WIKI_API}' as '${WIKI_API_USER_NAME}': ${result}: ${reason}"
