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

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=${WIKI_API_USER_PASS}" \
  --data-urlencode "lgdomain=${USERDOMAIN}" \
  --data-urlencode "lgtoken=${login_token}" \
  --output "${TMPFOLDER}/login-result.json" \
  --request "POST" \
  "${WIKI_API}?action=login&format=json"

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

reason="$(jq -r ".login.reason" < <(stcat "${TMPFOLDER}/login-result.json"))"
die 1 "Login failed to '$WIKI_API' as '$WIKI_API_USER_NAME': ${result}: ${reason}"
