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

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

default_new_file="${TMPFOLDER}/fetched-wiki-page"
if [[ -z "${2-}" || "${1-}" =~ (-h|--help) ]]; then
  usage
fi

WIKI_URL="$1"
page_title="$2"
new_file="${3-"${default_new_file}"}"

check_vars_exist page_title

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

#mw-login-test "$WIKI_URL"

log_run info mw-fetch "${WIKI_URL}" "${page_title}" "${new_file}"

## time-of-check to time-of-use TOCTOU
## Check for pending edits only after page was fetched.
## Checking for pending edits before fetching page would leave room for
## making a pending edit after the page has been fetched.
## This ensures that the fetched edit was not pending, i.e. confirmed.
mw-page-pending-check "${WIKI_URL}" "${page_title}"

filename="${new_file}"
tempfile="${TMPFOLDER}/temp-edit-file"

replace_all_except_first() {
  local linenum

  if ! grep --line-number -- "${search}" "${filename}" >/dev/null 2>&1; then
    return 0
  fi

  linenum="$(grep --line-number -- "${search}" "${filename}")"
  linenum="$(head -n1 <<<"${linenum}")"
  linenum="$(cut -d: -f1 <<<"${linenum}")"

  # If {{project_name_long}} is found in the file
  if [ -n "${linenum}" ]; then
    # Print the lines from the beginning of the file to the line number where the first occurrence is found
    awk -v n="${linenum}" 'NR<=n' -- "${filename}" >"${tempfile}"

    # Replace subsequent occurrences of {{project_name_long}} with {{project_name_short}}
    # and append them to the temporary file
    awk -v n="${linenum}" 'NR>n' -- "${filename}" | sed "s/${search}/${replace}/g" >>"${tempfile}"

    # Move the temporary file to the original file
    mv -- "${tempfile}" "${filename}"
  fi
}

search="{{project_name_long}}"
replace="{{project_name_short}}"
replace_all_except_first

search="{{project_name_gateway_long}}"
replace="{{project_name_gateway_short}}"
replace_all_except_first

search="{{project_name_workstation_long}}"
replace="{{project_name_workstation_short}}"
replace_all_except_first

search="{{q_project_name_long}}"
replace="{{q_project_name_short}}"
replace_all_except_first

search="{{non_q_project_name_long}}"
replace="{{non_q_project_name_short}}"
replace_all_except_first

search="{{project_name_customworkstation_long}}"
replace="{{project_name_customworkstation_short}}"
replace_all_except_first

log_run info mw-edit "${WIKI_URL}" "${filename}" "${page_title}"
