#!/usr/bin/env bash
# BTCProxy N1 v5.9.0-rc2 — encrypted bundle / unattended package stages / guarded cutover.
# Usage: sudo bash n1-upgrade-v59.sh --site-id XL [--preflight-only]
# Package: https://files.shenqianqian.com/btcproxy/n1/config/n1-config-v59.tar.gz.gpg
# Requires: existing root-run n1agent service on Debian Bookworm arm64.
set -Eeuo pipefail
set +x
umask 077

VERSION='5.9.0-rc2'
COMMIT='fd8b75acb638995c2a97d38bb7fe4670738f5908'
BIN_BASE="https://files.shenqianqian.com/btcproxy/vps/staging/v${VERSION}-${COMMIT}"
DEFAULT_BUNDLE_URL='https://files.shenqianqian.com/btcproxy/n1/config/n1-config-v59.tar.gz.gpg'
CONFIG_DIR='/etc/btcproxy-agent'
SITE_ID=''
BUNDLE_URL="$DEFAULT_BUNDLE_URL"
BUNDLE_FILE=''
PREFLIGHT_ONLY=0
TMP=''
BACKUP=''
ROLLBACK_NEEDED=0

info()  { printf '[N1 V5.9] %s\n' "$*"; }
error() { printf '[N1 V5.9] ERROR: %s\n' "$*" >&2; }
abort() { error "$*"; exit 1; }

usage() {
  cat <<'EOF'
Usage: bash n1-upgrade-v59.sh [--site-id XL] [--preflight-only]
       [--bundle-url https://.../n1-config-v59.tar.gz.gpg]
       [--bundle-file /root/n1-config-v59.tar.gz.gpg]

All installer prerequisites, download, decryption and validation finish BEFORE
stopping n1agent. Without --site-id, the site ID is prompted interactively.
The encrypted bundle password is ALWAYS prompted through /dev/tty.
EOF
}

while (($#)); do
  case "$1" in
    --site-id)       (($# >= 2)) || abort '--site-id needs a value'; SITE_ID=$2; shift 2 ;;
    --bundle-url)    (($# >= 2)) || abort '--bundle-url needs a value'; BUNDLE_URL=$2; shift 2 ;;
    --bundle-file)   (($# >= 2)) || abort '--bundle-file needs a value'; BUNDLE_FILE=$2; shift 2 ;;
    --preflight-only) PREFLIGHT_ONLY=1; shift ;;
    -h|--help) usage; exit 0 ;;
    *) abort "Unknown argument: $1" ;;
  esac
done

rollback() {
  error 'Upgrade verification failed. Restoring the previous N1 binary and configuration.'
  systemctl stop n1agent >/dev/null 2>&1 || true
  install -m 755 "$BACKUP/n1agent" /usr/local/bin/n1agent || error 'Binary restore FAILED'
  if [[ -d "$BACKUP/btcproxy-agent" ]]; then
    rm -rf -- "$CONFIG_DIR"
    cp -a "$BACKUP/btcproxy-agent" "$CONFIG_DIR" || error 'Config restore FAILED'
  fi
  cp -a "$BACKUP/n1agent.service" /etc/systemd/system/n1agent.service || true
  systemctl daemon-reload || true
  systemctl start n1agent || error 'Old n1agent could NOT be restarted'
  systemctl is-active n1agent || true
  error "Rollback files: $BACKUP"
}
cleanup() {
  local rc=$?
  trap - EXIT
  if ((ROLLBACK_NEEDED)); then rollback; rc=1; fi
  if [[ -n "$TMP" && -d "$TMP" ]]; then
    if command -v gpgconf >/dev/null 2>&1; then
      gpgconf --homedir "$TMP/gnupg" --kill gpg-agent >/dev/null 2>&1 || true
    fi
    rm -rf -- "$TMP"
  fi
  exit "$rc"
}
trap cleanup EXIT

[[ $(id -u) -eq 0 ]] || abort 'Please execute as root'
[[ $(uname -m) == aarch64 ]] || abort 'Expected ARM64 (aarch64) N1'
[[ -r /etc/os-release ]] || abort 'OS version unavailable'
# shellcheck disable=SC1091
. /etc/os-release
[[ "${VERSION_CODENAME:-}" == bookworm ]] || abort 'This package installer only supports Debian 12 / Bookworm'
for cmd in bash python3 curl tar openssl sha256sum awk grep systemctl ss; do
  command -v "$cmd" >/dev/null || abort "Required command missing: $cmd"
done
[[ -f /etc/systemd/system/n1agent.service ]] || abort 'Existing n1agent.service missing'
[[ -s /usr/local/bin/n1agent ]] || abort 'Existing /usr/local/bin/n1agent missing'
[[ -d "$CONFIG_DIR" ]] || abort "Missing $CONFIG_DIR"
[[ $(systemctl show n1agent -p User --value) == '' || $(systemctl show n1agent -p User --value) == root ]] || abort 'Non-root service user: manual review required'
[[ $(systemctl show n1agent -p EnvironmentFiles --value) == *"$CONFIG_DIR/agent.env"* ]] || abort 'systemd n1agent service is not loading /etc/btcproxy-agent/agent.env'

if [[ -z "$SITE_ID" ]]; then
  [[ -r /dev/tty ]] || abort 'Interactive terminal required for site ID'
  read -r -p '场地 ID（例如 XL）: ' SITE_ID </dev/tty
fi
[[ "$SITE_ID" =~ ^[A-Za-z0-9._-]{1,64}$ ]] || abort 'Invalid site ID: allowed characters A-Z a-z 0-9 . _ - (1 to 64)'
if [[ -z "$BUNDLE_FILE" ]]; then
  [[ "$BUNDLE_URL" == https://* ]] || abort 'Encrypted bundle URL must be HTTPS'
else
  [[ -s "$BUNDLE_FILE" ]] || abort "Bundle file not found: $BUNDLE_FILE"
fi

TMP=$(mktemp -d /root/.n1-v59-upgrade.XXXXXXXX)
chmod 700 "$TMP"

# One isolated apt source for this installation; NEVER rewrite global APT sources.
ensure_deps() {
  local needed=() mirror aptlist opts=() success=0
  command -v argon2 >/dev/null 2>&1 || needed+=(argon2)
  command -v gpg >/dev/null 2>&1 || needed+=(gpg)
  ((${#needed[@]} == 0)) && { info 'argon2 and GPG available, skipping APT'; return; }
  command -v apt-get >/dev/null || abort 'apt-get required to install missing dependencies'
  aptlist="$TMP/debian-mirror.list"
  opts=(-o "Dir::Etc::sourcelist=$aptlist" -o 'Dir::Etc::sourceparts=-'
        -o 'Acquire::Retries=1' -o 'Acquire::http::Timeout=15'
        -o 'Acquire::https::Timeout=15' -o 'DPkg::Lock::Timeout=45')
  for mirror in 'https://mirrors.ustc.edu.cn/debian/' 'https://mirrors.tuna.tsinghua.edu.cn/debian/'; do
    info "Installing ${needed[*]} with temporary mirror $mirror"
    printf 'deb %s bookworm main\n' "$mirror" > "$aptlist"
    if apt-get "${opts[@]}" update && apt-get "${opts[@]}" install -y --no-install-recommends "${needed[@]}"; then
      success=1
      break
    fi
    error "APT mirror failed: $mirror; trying fallback"
  done
  ((success == 1)) || abort 'Neither domestic APT mirror installed the dependencies; production N1 has NOT been stopped'
  command -v argon2 >/dev/null || abort 'argon2 CLI missing after installation'
  command -v gpg >/dev/null || abort 'gpg CLI missing after installation'
}
ensure_deps

info 'Obtaining encrypted configuration bundle'
if [[ -n "$BUNDLE_FILE" ]]; then
  cp -- "$BUNDLE_FILE" "$TMP/config.tar.gz.gpg"
else
  curl --fail --location --silent --show-error --retry 2 \
    --connect-timeout 10 --max-time 90 "$BUNDLE_URL" -o "$TMP/config.tar.gz.gpg" \
    || abort "Could not download encrypted bundle: $BUNDLE_URL"
fi
[[ -s "$TMP/config.tar.gz.gpg" ]] || abort 'Downloaded bundle is empty'
[[ $(stat -c %s "$TMP/config.tar.gz.gpg") -le 1048576 ]] || abort 'Encrypted bundle too large (>1 MiB)'

[[ -r /dev/tty ]] || abort 'Interactive terminal required to enter encryption password'
read -r -s -p '请输入配置包解密密码（不会显示）: ' PASSPHRASE </dev/tty
printf '\n' >/dev/tty
[[ -n "$PASSPHRASE" ]] || abort 'Empty bundle password not allowed'
mkdir -m 700 "$TMP/gnupg"
# Password is carried only on inherited file descriptor 3, not argv/env/logs.
if ! gpg --homedir "$TMP/gnupg" --no-options --batch --yes \
    --pinentry-mode loopback --no-symkey-cache --passphrase-fd 3 \
    --output "$TMP/config.tar.gz" --decrypt "$TMP/config.tar.gz.gpg" \
    3< <(printf '%s\n' "$PASSPHRASE"); then
  unset PASSPHRASE
  abort 'Bundle decryption/authenticity verification failed (wrong password or damaged archive)'
fi
unset PASSPHRASE

# STRICTLY validate members before reading. Never `tar -x` from untrusted network data.
mkdir -m 700 "$TMP/config-input"
python3 - "$TMP/config.tar.gz" "$TMP/config-input" <<'PY'
import os, pathlib, sys, tarfile
archive = pathlib.Path(sys.argv[1])
outdir = pathlib.Path(sys.argv[2])
expected = {"agent.env", "ca-bundle-v2.crt", "config.yaml"}
limits = {"agent.env": 64*1024, "ca-bundle-v2.crt": 128*1024, "config.yaml": 128*1024}
with tarfile.open(archive, mode="r:gz") as tf:
    members = tf.getmembers()
    if set(m.name for m in members) != expected or len(members) != 3:
        sys.exit("ERROR: bundle must contain exactly agent.env, ca-bundle-v2.crt, config.yaml")
    for m in members:
        if not m.isfile() or m.name not in expected or m.size <= 0 or m.size > limits[m.name]:
            sys.exit("ERROR: invalid bundle file type or size: " + m.name)
        f = tf.extractfile(m)
        if f is None:
            sys.exit("ERROR: unreadable bundle file: " + m.name)
        data = f.read(limits[m.name] + 1)
        if len(data) != m.size:
            sys.exit("ERROR: bundle size mismatch: " + m.name)
        path = outdir / m.name
        fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
        with os.fdopen(fd, "wb") as dest:
            dest.write(data)
print("Encrypted bundle structure verified: 3 regular files")
PY

info 'Validating N1 configuration (site, port, CA path, token reference)'
python3 - "$TMP/config-input/config.yaml" "$TMP/config-input/agent.env" "$SITE_ID" "$TMP/config.ready.yaml" <<'PY'
from pathlib import Path
import re, sys
cfg_path, env_path, site, dst = map(Path, (sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]))
s = cfg_path.read_text(encoding="utf-8")
# Preserve all routes, ports, Web settings; change ONLY site ID and CA bundle path.
s, n = re.subn(r'(?m)^([ \t]*client_id[ \t]*:[ \t]*).*$',
                lambda m: m.group(1) + '"' + str(site) + '"', s)
if n != 1: sys.exit("ERROR: expected exactly one client_id field")
hosts = re.findall(r'(?m)^[ \t]*host[ \t]*:[ \t]*["\']?([^\s"\']+)', s)
if not hosts or any(h != "v4.shenqianqian.com" for h in hosts):
    sys.exit("ERROR: only v4.shenqianqian.com may be enabled by this fixed-version installer")
if not re.search(r'(?m)^[ \t]*host:[ \t]*["\']?v4\.shenqianqian\.com["\']?[ \t]*\r?\n[ \t]*port:[ \t]*443[ \t]*(?:#.*)?$', s):
    sys.exit("ERROR: V4 server port must be 443")
s, n = re.subn(r'(?m)^([ \t]*ca_file[ \t]*:[ \t]*).*$',
                lambda m: m.group(1) + '"/etc/btcproxy-agent/ca-bundle-v2.crt"', s)
if n != 1: sys.exit("ERROR: expected exactly one tls.ca_file")
if not re.search(r'(?m)^\s*token:\s*["\']?\$\{BTCPROXY_TUNNEL_TOKEN\}', s):
    sys.exit("ERROR: missing auth.token environment reference in config.yaml")
env = env_path.read_text(encoding="utf-8")
values = re.findall(r'(?m)^[ \t]*BTCPROXY_TUNNEL_TOKEN[ \t]*=[ \t]*(.+)[ \t]*$', env)
if len(values) != 1 or not values[0].strip().strip('"\''):
    sys.exit("ERROR: missing/non-unique/nonempty BTCPROXY_TUNNEL_TOKEN in agent.env")
if any(line.startswith("-----BEGIN ") for line in env.splitlines()):
    sys.exit("ERROR: agent.env contains unexpected PEM material")
dst.write_text(s, encoding="utf-8")
print("Configuration OK: site=%s, host=v4.shenqianqian.com:443" % site)
PY
openssl x509 -in "$TMP/config-input/ca-bundle-v2.crt" -noout >/dev/null \
  || abort 'CA bundle does not contain a valid PEM certificate'

info "Downloading matching N1 binary from ${BIN_BASE}"
mkdir -m 700 "$TMP/n1"
curl --fail --location --silent --show-error --retry 2 --connect-timeout 10 --max-time 120 \
  "$BIN_BASE/n1/n1agent" -o "$TMP/n1/n1agent" \
  || abort 'N1 binary download failed: verify staging release URL'
curl --fail --location --silent --show-error --retry 2 --connect-timeout 10 --max-time 60 \
  "$BIN_BASE/SHA256SUMS" -o "$TMP/SHA256SUMS" \
  || abort 'SHA256SUMS download failed'
expected=$(awk '$2=="n1/n1agent" {print $1}' "$TMP/SHA256SUMS")
[[ "$expected" =~ ^[0-9a-fA-F]{64}$ ]] || abort 'Invalid/duplicate SHA256 for n1/n1agent'
actual=$(sha256sum "$TMP/n1/n1agent" | awk '{print $1}')
[[ "${expected,,}" == "${actual,,}" ]] || abort 'N1 binary SHA256 mismatch'
[[ $(stat -c %s "$TMP/n1/n1agent") -lt 30000000 ]] || abort 'Unreasonable N1 binary size'
grep -aFq "$COMMIT" "$TMP/n1/n1agent" || abort 'N1 binary missing expected commit marker'
info "N1 binary verified: SHA256 ${actual}"

if ((PREFLIGHT_ONLY)); then
  info 'Preflight PASSED. No production binary or configuration changed; service was not restarted.'
  exit 0
fi

# Files protected while running as root. Backup the WHOLE previous config directory.
BACKUP="/root/n1-backup-$(date +%Y%m%d-%H%M%S)-$$"
install -d -m 700 "$BACKUP"
cp -a /usr/local/bin/n1agent "$BACKUP/n1agent"
cp -a "$CONFIG_DIR" "$BACKUP/btcproxy-agent"
cp -a /etc/systemd/system/n1agent.service "$BACKUP/n1agent.service"
printf '%s\n' "$BACKUP" > /root/n1-last-backup
info "Backup completed: $BACKUP"

ROLLBACK_NEEDED=1
info 'Cutover: stopping N1 once and atomically replacing 4 files'
systemctl stop n1agent
install -m 755 "$TMP/n1/n1agent" /usr/local/bin/n1agent
install -m 600 "$TMP/config.ready.yaml" "$CONFIG_DIR/config.yaml"
install -m 600 "$TMP/config-input/agent.env" "$CONFIG_DIR/agent.env"
install -m 644 "$TMP/config-input/ca-bundle-v2.crt" "$CONFIG_DIR/ca-bundle-v2.crt"
systemctl start n1agent || abort 'New n1agent failed to start'
sleep 8
systemctl is-active --quiet n1agent || abort 'New n1agent is not active'
for port in 13666 8088; do
  ss -lntp | grep -Eq ":${port}[[:space:]]" || abort "N1 port $port is not listening"
done
# Immediate detected auth failures are a hard deployment error. No failure is NOT a pass for mining shares.
if journalctl -u n1agent --since '20 seconds ago' --no-pager 2>/dev/null \
    | grep -E 'AUTH_REJECTED|health=CONFIG_ERROR' >/dev/null; then
  abort 'AUTH_REJECTED / CONFIG_ERROR observed after cutover'
fi
ROLLBACK_NEEDED=0
info "CUTOVER OK: N1 is active; 13666/8088 listen; no immediate auth rejection. Backup: $BACKUP"
info 'Verify actual mining on V4 (working/accepted shares). Startup alone does not prove mining.'
systemctl status n1agent --no-pager -l | head -n 20 || true
journalctl -u n1agent --since '20 seconds ago' --no-pager \
  | grep -Ei 'endpoint|connected|AUTH_REJECTED|CONFIG_ERROR|web listening|agent listening' \
  | tail -n 20 || true
