#!/usr/bin/env bash
# TXC v0.26.2 emergency upgrade — Send To Many negative-amount fix.
# Swaps texitcoind/texitcoin-cli in place on a running node, then restarts it
# ONCE with -startclean so the Omni layer recounts every token balance under the
# fixed rules. That reparse voids the three Nov 4, 2026 thefts and returns the TSD to its owners.
#
# Usage (as root or with sudo):
#   ZIP_URL=<release zip url> ZIP_SHA256=<sha256> bash txc-stm-fix-upgrade.sh
# Safe to re-run. Never touches wallets, config, stratum, or other daemons.
set -euo pipefail

ATTACKER="TedE9NgHHydQf9iLZb6H9XXNHEwkSLxDwe"
PROPERTY=39
EXPLOIT_TXS=(
  db3e67d11f7f6aadbd9f99ee235e8cb9673895434892d343b04bf86925dde581
  fe594d56041263917bee4c3d46ffc4a77b13dde07f57e603b6715fbe625379a6
  da468ac9889c911dbc169f4a5dfcb2dfca85e9ec441f2439562f3770046e4dff
)

say()  { printf "\033[1;36m[stm-fix]\033[0m %s\n" "$*"; }
die()  { printf "\033[1;31m[stm-fix] STOP:\033[0m %s\n" "$*"; exit 1; }

WAIT_SECONDS="${WAIT_SECONDS:-3600}"
[[ "$WAIT_SECONDS" =~ ^[1-9][0-9]*$ ]] || die "WAIT_SECONDS must be a positive integer"
SUDO=""; [[ $EUID -ne 0 ]] && SUDO="sudo"

# --- Find the live daemon, its user and its arguments -----------------------
PID=$(pgrep -xo texitcoind || true)
[[ -n "$PID" ]] || die "texitcoind is not running here"
DAEMON=$(readlink -f /proc/$PID/exe)
RUN_USER=$(ps -o user= -p "$PID" | tr -d ' ')
mapfile -d '' ARGS < /proc/$PID/cmdline
CLI_ARGS=()
for a in "${ARGS[@]:1}"; do
  case "$a" in -datadir=*|-conf=*|-testnet|-regtest) CLI_ARGS+=("$a");; esac
done
BIN_DIR=$(dirname "$DAEMON")
CLI="$BIN_DIR/texitcoin-cli"; [[ -x "$CLI" ]] || CLI=$(command -v texitcoin-cli || true)
[[ -x "$CLI" ]] || die "texitcoin-cli not found next to $DAEMON"
UNIT=$(systemctl list-units --type=service --state=running --no-legend 2>/dev/null \
  | awk '{print $1}' | while read -r u; do
      if [[ "$(systemctl show -p MainPID --value "$u")" == "$PID" ]]; then echo "$u"; fi; done | head -1 || true)
# Always switch to the daemon user; as root $SUDO is empty and "-H -u" alone is not a command.
rpc() { sudo -H -u "$RUN_USER" "$CLI" "${CLI_ARGS[@]}" "$@"; }
say "daemon $DAEMON (pid $PID, user $RUN_USER, service ${UNIT:-none})"
say "current: $("$DAEMON" -version | head -1)"

already_updated() {
  [[ "$1" =~ v0\.26\.2([^0-9.]|$) && "$2" == "1.0.0" ]]
}
RUNNING_VERSION=$("$DAEMON" -version | head -1)
RUNNING_OMNI=$(rpc omni_getinfo 2>/dev/null | python3 -c 'import sys,json;print(json.load(sys.stdin).get("omnicoreversion",""))' 2>/dev/null || true)
BACKUP="none (verification-only run)"
if already_updated "$RUNNING_VERSION" "$RUNNING_OMNI"; then
  say "Already v0.26.2 / Omni 1.0.0 — verification only; no download, stop, swap or new recount"
else
[[ -n "${ZIP_URL:-}" && -n "${ZIP_SHA256:-}" ]] || die "set ZIP_URL and ZIP_SHA256"
# --- Download + verify before touching anything -----------------------------
WORK=$(mktemp -d /tmp/stm-fix.XXXX)
curl -fsSL "$ZIP_URL" -o "$WORK/rel.zip"
echo "$ZIP_SHA256  $WORK/rel.zip" | sha256sum -c - || die "checksum mismatch — nothing changed"
unzip -q "$WORK/rel.zip" -d "$WORK/x"
NEW="$WORK/x/archive/artifacts/usr/local/bin"
[[ -x "$NEW/texitcoind" && -x "$NEW/texitcoin-cli" ]] || die "zip layout wrong — nothing changed"
"$NEW/texitcoind" -version | head -1 | grep -q "v0.26.2" || die "zip is not v0.26.2 — nothing changed"

# --- Graceful stop, backup, swap ---------------------------------------------
STAMP=$(date -u +%Y%m%dT%H%M%SZ)
BACKUP="$BIN_DIR/rollback-$STAMP"
$SUDO mkdir -p "$BACKUP"
$SUDO cp -a "$DAEMON" "$CLI" "$BACKUP/"
say "backup saved in $BACKUP"
say "stopping gracefully"
# Use systemd when it owns the daemon so Restart= cannot relaunch the old binary.
if [[ -n "$UNIT" ]]; then $SUDO systemctl stop "$UNIT" || true; else rpc stop || true; fi
for _ in $(seq 1 180); do kill -0 "$PID" 2>/dev/null || break; sleep 2; done
kill -0 "$PID" 2>/dev/null && die "daemon did not stop in 6 minutes — not swapping (still old version)"
$SUDO install -m 0755 "$NEW/texitcoind" "$DAEMON"
$SUDO install -m 0755 "$NEW/texitcoin-cli" "$CLI"

# --- Restart once with -startclean (Omni recount) ---------------------------
# NO_STARTCLEAN=1 proves the in-place path: a normal restart must trigger the
# recount by itself via the Omni DB version bump (auditor rollout condition 1).
if [[ "${NO_STARTCLEAN:-0}" == "1" ]]; then
  if [[ -n "$UNIT" ]]; then
    $SUDO systemctl start "$UNIT"
  else
    sudo -H -u "$RUN_USER" nohup "$DAEMON" "${ARGS[@]:1}" >/dev/null 2>&1 &
  fi
  say "restarted normally (NO_STARTCLEAN=1); expect 'Loading persistent state: NONE (client version changed)' in debug.log"
elif [[ -n "$UNIT" ]]; then
  DROPIN="/etc/systemd/system/$UNIT.d/zz-stm-startclean.conf"
  ORIG_EXEC=$(systemctl show -p ExecStart --value "$UNIT" | sed -n 's/.*argv\[\]=\([^;]*\);.*/\1/p')
  [[ -n "$ORIG_EXEC" ]] || die "could not read ExecStart for $UNIT; start manually with -startclean"
  $SUDO mkdir -p "$(dirname "$DROPIN")"
  printf '[Service]\nExecStart=\nExecStart=%s -startclean\n' "$ORIG_EXEC" | $SUDO tee "$DROPIN" >/dev/null
  $SUDO systemctl daemon-reload
  $SUDO systemctl start "$UNIT"
  sleep 20
  $SUDO rm -f "$DROPIN"; $SUDO systemctl daemon-reload   # next restart is normal
else
  sudo -H -u "$RUN_USER" nohup "$DAEMON" "${ARGS[@]:1}" -startclean >/dev/null 2>&1 &
fi
[[ "${NO_STARTCLEAN:-0}" == "1" ]] || say "restarted with -startclean; waiting for the Omni recount (can take a while)"
fi

recount_ready() {
  rpc getblockchaininfo | python3 -c 'import sys,json; d=json.load(sys.stdin); sys.exit(0 if d.get("initialblockdownload") is False and d.get("blocks") == d.get("headers") and isinstance(d.get("blocks"), int) else 1)'
}
DEADLINE=$((SECONDS + WAIT_SECONDS))
while (( SECONDS < DEADLINE )); do
  if recount_ready >/dev/null 2>&1 && rpc omni_getinfo >/dev/null 2>&1; then break; fi
  sleep 10
done
recount_ready && rpc omni_getinfo >/dev/null 2>&1 || die "node not synced and Omni-ready within ${WAIT_SECONDS}s — no balance verdict; the node may still be recounting; inspect its log and rerun verification later"

# --- Verify the fix took ----------------------------------------------------
FAIL=0
check_failed() { say "CHECK FAILED: $*"; FAIL=1; }
CURRENT_VERSION=$("$DAEMON" -version | head -1)
say "Core version: $CURRENT_VERSION"
[[ "$CURRENT_VERSION" =~ v0\.26\.2([^0-9.]|$) ]] || check_failed "Core version is not v0.26.2"
bal() { rpc omni_getbalance "$1" "$PROPERTY" | python3 -c 'import sys,json;print(json.load(sys.stdin)["balance"])'; }
BAL=$(bal "$ATTACKER")
say "attacker TSD balance: $BAL (should be 41.74532 or less)"
# The three drained wallets must have their balances back (exact pre-theft amounts).
for pair in TcShsWtgfq7RYcHVnZDAUDYRgFTfdVVkxi:14920 TgtuZR7BJ8wBj6KfDYCVJWghY2H3sdFhE5:15909.67 ToKe3KyyqpH7uQiEuGvJp2Mj9iBRDTTCuP:53548.156565; do
  a=${pair%%:*}; want=${pair##*:}; got=$(bal "$a")
  say "victim $a: $got (needs at least $want)"
  python3 -c "import sys; sys.exit(0 if float('$got') >= $want else 1)" || check_failed "victim $a balance $got below $want; reconcile later legitimate activity"
done
python3 -c "import sys; sys.exit(0 if float('$BAL') <= 41.74532 else 1)" || check_failed "attacker balance $BAL above seed maximum 41.74532"
# Auditor sign-off checks: Omni layer 1.0.0, the three thefts recorded as invalid.
OMNIVER=$(rpc omni_getinfo | python3 -c 'import sys,json;print(json.load(sys.stdin).get("omnicoreversion",""))')
say "omni layer version: $OMNIVER (needs 1.0.0)"
[[ "$OMNIVER" == "1.0.0" ]] || check_failed "Omni version is $OMNIVER, expected 1.0.0"
# omni_gettransaction needs a loaded wallet. Use a dedicated key-free, blank
# wallet so no real wallet or key is ever opened or created for these checks.
if ! rpc -rpcwallet=audit-readonly getwalletinfo >/dev/null 2>&1; then
  rpc loadwallet audit-readonly >/dev/null 2>&1 || rpc createwallet audit-readonly true true >/dev/null \
    || die "could not open key-free audit wallet; wallet support may be disabled — node upgraded, verify manually"
fi
say "key-free audit wallet ready (no private keys)"
rpcw() { rpc -rpcwallet=audit-readonly "$@"; }
for tx in db3e67d11f7f6aadbd9f99ee235e8cb9673895434892d343b04bf86925dde581 \
          fe594d56041263917bee4c3d46ffc4a77b13dde07f57e603b6715fbe625379a6 \
          da468ac9889c911dbc169f4a5dfcb2dfca85e9ec441f2439562f3770046e4dff; do
  v=$(rpcw omni_gettransaction "$tx" | python3 -c 'import sys,json;d=json.load(sys.stdin);print(d.get("valid"),"|",d.get("invalidreason",""))')
  say "theft ${tx:0:8}: valid=$v"
  [[ "$v" == "False | Receiver amount is zero or above the maximum" ]] || check_failed "theft $tx has unexpected validity/reason: $v"
done
REVOKE="f67ea9c05acb33cfcb7ddabe7606ceda8e277bd1a83d37fda838c2c9088116a2"
say "30,000 TSD revoke $REVOKE: $(rpcw omni_gettransaction "$REVOKE" | tr -d '\n')"
SNAPSHOT_OK=0
for _ in $(seq 1 5); do
  TIP_BEFORE=$(rpc getbestblockhash)
  TIP_HEIGHT=$(rpc getblockcount)
  CONSENSUS=$(rpc omni_getcurrentconsensushash | tr -d '\n ')
  TIP_AFTER=$(rpc getbestblockhash)
  if [[ "$TIP_BEFORE" == "$TIP_AFTER" ]]; then SNAPSHOT_OK=1; break; fi
done
[[ "$SNAPSHOT_OK" == 1 ]] || die "tip changed during evidence capture — retry the evidence checks"
say "consensus evidence: getblockcount=$TIP_HEIGHT getbestblockhash=$TIP_AFTER consensus=$CONSENSUS"
say "Compare ONLY with another synced node at this exact height AND block hash. A different tip is not a match or mismatch verdict."
[[ "$FAIL" == "0" ]] || die "one or more checks failed — see CHECK FAILED lines above; send full output to the team"
say "Node checks passed — not auditor sign-off. Still collect the 37 honest Send To Many verdicts, the 30,000 revoke verdict, and matching same-tip evidence from a second node. Keep the bridge paused. Rollback copies: $BACKUP"
