#!/bin/bash

set -e

source /usr/share/mediawiki-shell/common

check_vars_exist WIKI_URL wiki_page_item

[[ -v wiki_source_api ]] || wiki_source_api="${WIKI_URL}/api.php"

# WIKI_URL="$WIKI_URL" \
#    mw-logout
# WIKI_URL="$WIKI_URL" \
#    mw-login

wiki_article_to_fetch="$wiki_page_item" \
wiki_fetch_to_file="$TMPFOLDER/fetched-wiki-page" \

log_run env WIKI_URL="$WIKI_URL" wiki_fetch_to_file="$wiki_fetch_to_file" mw-fetch

## 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.
page_pending_status_json=$(\
   $curl \
      $curl_opts \
      "${wiki_source_api}?format=json&action=query&prop=info%7Cflagged&titles=$wiki_page_item"
)

if echo "$page_pending_status_json" | jq | grep -q pending_since ; then
   echo "$0: WARNING: '$WIKI_URL' '$wiki_page_item' page has PENDING EDITS!"
   exit 10
fi

filename="$TMPFOLDER/fetched-wiki-page"
tempfile="$TMPFOLDER/temp-edit-file"

replace_all_except_first() {
   if ! grep --quiet -n "$search" "$filename" ; then
      return 0
   fi

   linenum=$(grep -n "$search" "$filename")
   linenum=$(echo "$linenum" | head -n1)
   linenum=$(echo "$linenum" | cut -d: -f1)

   # 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 env WIKI_URL="$WIKI_URL" mw-edit "$wiki_page_item" "$filename"
