#!/usr/bin/env bash
set -uo pipefail
UPD="${WSP_UPD_DIR:-/var/lib/trinity/App_Data/update}"; LIB="${WSP_UPD_LIB:-/usr/local/lib/trinity-updater}"
CONF="${WSP_UPD_CONF:-/etc/trinity/cluster.conf}"; VERFILE="${WSP_UPD_VERFILE:-/opt/trinity/VERSION}"; ACCT="${WSP_UPD_ACCOUNT:-trinity}"
if [ -z "${WSP_UPD_ACCOUNT:-}" ] && ! id "$ACCT" >/dev/null 2>&1 && id wsp >/dev/null 2>&1; then ACCT=wsp; fi
TRIES="${WSP_UPD_HEALTH_TRIES:-36}"; PEERWAIT="${WSP_UPD_PEER_WAIT:-2700}"
as_wsp() { if command -v runuser >/dev/null 2>&1; then runuser -u "$ACCT" -- "$@"; else su -s /bin/sh "$ACCT" -c 'exec "$0" "$@"' -- "$@"; fi; }
id "$ACCT" >/dev/null 2>&1 || { echo "no account $ACCT" >&2; exit 0; }
now() { date -u +%Y-%m-%dT%H:%M:%SZ; }
installed() { sed -n 's/^package=//p' "$VERFILE" 2>/dev/null | head -n1; }
port() { local p; p=$(systemctl show trinity-portal -p Environment 2>/dev/null | grep -o 'WSP_HTTPS_PORT=[0-9]*' | cut -d= -f2); echo "${WSP_UPD_PORT:-${p:-443}}"; }
jget() { python3 -I -c 'import json,sys
try: d=json.load(open(sys.argv[1]))
except Exception: d={}
for k in sys.argv[2].split("."): d=d.get(k) if isinstance(d,dict) else None
print("" if d is None else d)' "$1" "$2" 2>/dev/null; }
verify_sig() {
  printf 'mwsmon-update-v1\n%s\nlinux\n%s' "$1" "$2" > "$4/msg"
  echo "$3" | base64 -d > "$4/sig" 2>/dev/null
  openssl dgst -sha256 -verify "$LIB/update-key.pem" -signature "$4/sig" "$4/msg" >/dev/null 2>&1
}
CLUSTER=0; ACTIVE=1; ME="$(hostname)"; OTHER=""; BASE=""
if [ -f "$CONF" ]; then
  CLUSTER=1
  conf() { sed -n "s/^[[:space:]]*$1=\"\{0,1\}\([A-Za-z0-9._:-]*\)\"\{0,1\}.*/\1/p" "$CONF" | head -n1; }
  N1="$(conf NODE1)"; N2="$(conf NODE2)"; VIP="$(conf VIP)"; ME="${WSP_UPD_NODE:-$ME}"
  if [ "${ME,,}" = "${N1,,}" ] || [ "${ME%%.*}" = "$N1" ]; then OTHER="$N2"; else OTHER="$N1"; fi
  if [ -n "${WSP_UPD_ACTIVE:-}" ]; then ACTIVE="$WSP_UPD_ACTIVE"; elif mountpoint -q /var/lib/trinity; then ACTIVE=1; else ACTIVE=0; fi
  if [ "$ACTIVE" = 1 ]; then BASE="https://127.0.0.1:$(port)"; else BASE="https://$VIP:$(port)"; fi
  BASE="${WSP_UPD_PORTAL:-$BASE}"
  report() {
    # shellcheck disable=SC2086
    curl -sk --max-time 20 ${WSP_UPD_CURL_OPTS:-} -G "$BASE/update/node" --data-urlencode "version=$(installed)" --data-urlencode "state=$1" \
      --data-urlencode "target=${2:-}" --data-urlencode "message=${3:-}" --data-urlencode "active=$ACTIVE" 2>/dev/null
  }
fi

if [ "$CLUSTER" = 1 ] && [ "$ACTIVE" != 1 ]; then
  W=$(mktemp -d); chmod 700 "$W"; trap 'rm -rf "$W"' EXIT
  report idle "" "" > "$W/offer.json" || { echo "portal not reachable at $BASE" >&2; exit 0; }
  OV=$(jget "$W/offer.json" offer.version); OSHA=$(jget "$W/offer.json" offer.sha256); OSIG=$(jget "$W/offer.json" offer.sig)
  [ -n "$OV" ] || exit 0
  CUR="$(installed)"
  [ "$OV" != "$CUR" ] || exit 0
  [[ "$OV" =~ ^[0-9A-Za-z][0-9A-Za-z.+-]*$ ]] || exit 0
  if [ -n "$CUR" ] && [ "$(printf '%s\n%s\n' "$CUR" "$OV" | sort -V | tail -n1)" = "$CUR" ]; then exit 0; fi
  fail() { echo "$1" >&2; report failed "$OV" "$1" >/dev/null; exit 0; }
  [ -f "$LIB/update-key.pem" ] || fail "no vendor key on this node - updates cannot be verified (run install-trinity.sh --update from a package 0.12.8 or newer once)"
  report installing "$OV" "fetching the package from the portal" >/dev/null
  # shellcheck disable=SC2086
  curl -sk --max-time 1800 --max-filesize 1100000000 ${WSP_UPD_CURL_OPTS:-} -o "$W/pkg.tar.gz" "$BASE/update/node/package" || fail "the package could not be fetched from the portal ($BASE)"
  GOT=$(sha256sum "$W/pkg.tar.gz" | cut -d' ' -f1)
  [ "$GOT" = "$OSHA" ] || fail "SHA-256 of the fetched package does not match - not installed"
  verify_sig "$OV" "$OSHA" "$OSIG" "$W" || fail "vendor signature is not valid - not installed"
  mkdir "$W/x"; tar -xzf "$W/pkg.tar.gz" -C "$W/x" || fail "package cannot be unpacked"
  [ -f "$W/x/trinity/install-trinity.sh" ] || fail "the package has no installer"
  chmod +x "$W/x/trinity/install-trinity.sh"
  report installing "$OV" "vendor signature valid - installing the program files" >/dev/null
  "$W/x/trinity/install-trinity.sh" --update > "$W/log" 2>&1 || true
  if [ "$(installed)" = "$OV" ]; then
    [ -f "$W/x/trinity/trinity-updater" ] && install -m 755 "$W/x/trinity/trinity-updater" "$LIB/trinity-updater" 2>/dev/null
    report updated "$OV" "installed $OV (was ${CUR:-unknown})" >/dev/null; echo "installed $OV"
  else
    fail "the installer did not finish: $(tail -n 3 "$W/log" 2>/dev/null | tr '\n' ' ' | cut -c1-200)"
  fi
  exit 0
fi

[ -d "$UPD" ] || as_wsp mkdir -p "$UPD" 2>/dev/null || exit 0
printf '{"at":"%s","host":"%s","version":"1.1"}\n' "$(now)" "$ME" | as_wsp tee "$UPD/updater.json" >/dev/null
[ "$CLUSTER" = 1 ] && report idle "" "" >/dev/null
[ -f "$UPD/pending.json" ] || exit 0
W=$(mktemp -d); chmod 700 "$W"; trap 'rm -rf "$W"' EXIT
as_wsp cat "$UPD/pending.json" > "$W/pending.json" 2>/dev/null
P="$W/pending.json"; get() { jget "$P" "$1"; }
VER=$(get version); FROM=$(get from); FILE=$(get file); SHA=$(get sha256); SIG=$(get sig); PLAT=$(get platform)
step() { printf '%s %s\n' "$(date -u +%H:%M:%S)" "$1" | as_wsp tee -a "$UPD/progress.log" >/dev/null; as_wsp python3 -I -c 'import json,sys; l=open(sys.argv[1]).read().splitlines()[-60:]; json.dump({"version":sys.argv[2],"from":sys.argv[3],"step":sys.argv[4],"at":sys.argv[5],"log":l},open(sys.argv[6],"w"))' "$UPD/progress.log" "$VER" "$FROM" "$1" "$(now)" "$UPD/progress.json" 2>/dev/null; }
result() { as_wsp python3 -I -c 'import json,sys; json.dump({"version":sys.argv[1],"from":sys.argv[2],"ok":sys.argv[3]=="1","message":sys.argv[4],"finished":sys.argv[5]},open(sys.argv[6],"w"))' "$VER" "$FROM" "$1" "$2" "$(now)" "$UPD/result.json"; }
if [ "$CLUSTER" = 1 ]; then
  CUR="$(installed)"
  if [ -n "$CUR" ] && [ "$CUR" = "$VER" ]; then
    as_wsp rm -f "$UPD/pending.json"; result 1 "$VER is installed on this node already"; report updated "$VER" "already installed" >/dev/null; exit 0
  fi
  PF="$UPD/nodes/$(printf '%s' "$OTHER" | tr '[:upper:]' '[:lower:]' | tr -c 'a-z0-9._-' '_').json"
  as_wsp cat "$PF" > "$W/peer.json" 2>/dev/null || : > "$W/peer.json"
  PV=$(jget "$W/peer.json" version); PS=$(jget "$W/peer.json" state); PM=$(jget "$W/peer.json" message)
  if [ "$PV" != "$VER" ]; then
    AGE=$(( $(date +%s) - $(as_wsp stat -c %Y "$UPD/pending.json" 2>/dev/null || date +%s) ))
    if [ "$AGE" -gt "$PEERWAIT" ] || [ "$PS" = failed ]; then
      as_wsp rm -f "$UPD/pending.json"
      if [ "$PS" = failed ]; then MSG="the other node ($OTHER) could not install $VER: ${PM:-no message} - nothing was changed on this node"
      else MSG="the other node ($OTHER) did not install $VER within $((PEERWAIT / 60)) minutes (it reports ${PV:-nothing}) - nothing was changed on this node. Its updater must be installed (sudo ./install-trinity.sh --update from a package 0.12.8 or newer, once) and it must reach the portal over HTTPS"; fi
      : | as_wsp tee "$UPD/progress.log" >/dev/null; step "$MSG"; result 0 "$MSG"; report failed "$VER" "stopped: the other node is not updated" >/dev/null; exit 0
    fi
    [ -s "$UPD/progress.log" ] || : | as_wsp tee "$UPD/progress.log" >/dev/null
    step "waiting for the other node ($OTHER) to install $VER first (it reports ${PV:-nothing yet}${PS:+, $PS})"
    report waiting "$VER" "waiting for $OTHER" >/dev/null; exit 0
  fi
fi
as_wsp rm -f "$UPD/pending.json"
[ "$CLUSTER" = 1 ] || : | as_wsp tee "$UPD/progress.log" >/dev/null
[ "$CLUSTER" = 1 ] && { step "the other node ($OTHER) has $VER - installing on this node"; report installing "$VER" "installing" >/dev/null; }
step "checking the package $FILE (version $VER)"
[ "$PLAT" = linux ] || { result 0 "package is for $PLAT"; exit 0; }
[[ "$FILE" =~ ^package-[0-9A-Za-z.-]+\.tar\.gz$ ]] || { result 0 "invalid package name"; exit 0; }
[ -f "$LIB/update-key.pem" ] || { result 0 "no vendor key on this server - updates cannot be verified"; exit 0; }
as_wsp cat "$UPD/$FILE" > "$W/pkg.tar.gz" 2>/dev/null || { result 0 "package cannot be read"; exit 0; }
GOT=$(sha256sum "$W/pkg.tar.gz" | cut -d' ' -f1)
[ "$GOT" = "$SHA" ] || { result 0 "SHA-256 does not match"; exit 0; }
verify_sig "$VER" "$SHA" "$SIG" "$W" || { result 0 "vendor signature is not valid - not installed"; [ "$CLUSTER" = 1 ] && report failed "$VER" "vendor signature is not valid" >/dev/null; exit 0; }
step "vendor signature valid - unpacking"
tar -xzf "$W/pkg.tar.gz" -C "$W" || { result 0 "package cannot be unpacked"; exit 0; }
step "installing (install-trinity.sh --update keeps the previous program in /opt/trinity/app.old)"
[ -x "$W/trinity/install-trinity.sh" ] || chmod +x "$W/trinity/install-trinity.sh"
"$W/trinity/install-trinity.sh" --update > "$W/log" 2>&1 || true
tail -n 20 "$W/log" 2>/dev/null | while IFS= read -r line; do printf '%s   %s\n' "$(date -u +%H:%M:%S)" "$line"; done | as_wsp tee -a "$UPD/progress.log" >/dev/null
step "waiting for the portal to answer /healthz (up to 3 minutes)"
PORT=$(port)
for _ in $(seq 1 "$TRIES"); do
  sleep "${WSP_UPD_HEALTH_SLEEP:-5}"
  code=$(curl -sk -o /dev/null -w '%{http_code}' "${WSP_UPD_HEALTH_URL:-https://127.0.0.1:$PORT/healthz}" || true)
  if [ "$code" = 200 ] || [ "$code" = 503 ]; then
    step "done - the portal answers"; install -m 755 "$W/trinity/trinity-updater" "$LIB/trinity-updater" 2>/dev/null
    result 1 "updated $FROM -> $VER$([ "$CLUSTER" = 1 ] && echo " on both nodes ($OTHER first, then $ME)")"
    [ "$CLUSTER" = 1 ] && report updated "$VER" "installed $VER" >/dev/null
    exit 0
  fi
done
step "the portal did not answer - rolling back to $FROM"
if [ "$CLUSTER" = 1 ]; then
  if [ -d /opt/trinity/app.old ]; then rm -rf /opt/trinity/app.failed; mv /opt/trinity/app /opt/trinity/app.failed; mv /opt/trinity/app.old /opt/trinity/app; [ -f /opt/trinity/VERSION.old ] && cp -f /opt/trinity/VERSION.old /opt/trinity/VERSION; fi
  { pcs resource restart trinity-svc || pcs resource restart wsp-svc; } >/dev/null 2>&1 || true
  result 0 "the portal did not answer /healthz after the update - the previous program was put back on this node ($ME). The other node ($OTHER) has $VER installed: the two nodes differ until this is repaired - see the log"
  report failed "$VER" "rolled back on $ME" >/dev/null
  exit 0
fi
systemctl stop trinity-portal || true
if [ -d /opt/trinity/app.old ]; then rm -rf /opt/trinity/app.failed; mv /opt/trinity/app /opt/trinity/app.failed; mv /opt/trinity/app.old /opt/trinity/app; [ -f /opt/trinity/VERSION.old ] && cp -f /opt/trinity/VERSION.old /opt/trinity/VERSION; fi
systemctl start trinity-portal || true
result 0 "the portal did not answer /healthz after the update - version $FROM restored"
