#!/usr/bin/env bash
set +e
set +u
umask 077

STEP="STEP_050M07R09C_AUDIT_VM101_STORAGE_READ_ONLY"

TOKEN="e94a0859747d7b96f29c7fdafc2d0351ba603bb0a7e9e5a4"
ROOT="/opt/router-ops"
PUBROOT="$ROOT/public/r/$TOKEN"
PUBLIC_BASE="https://helena-background-beam-harry.trycloudflare.com/r/$TOKEN"

TS="$(date -u +%Y%m%d-%H%M%S)"
SLUG="${TS}_step050m07r09c_audit_vm101_storage_read_only"
REPORT_DIR="$PUBROOT/$SLUG"

TRYCF_REPORT="$PUBLIC_BASE/$SLUG/"
REPORT_TXT="${TRYCF_REPORT}report.txt"
FACTS_JSON="${TRYCF_REPORT}facts.json"

REMOTE_OUT="$REPORT_DIR/vm101-storage-audit.txt"
SSH_ERR="$REPORT_DIR/ssh.stderr"

mkdir -p "$REPORT_DIR"
cp -a "$0" "$REPORT_DIR/step.sh"
chmod 600 "$REPORT_DIR/step.sh"

ssh -T \
  -o BatchMode=yes \
  -o ConnectTimeout=10 \
  pve-mgts \
  "ssh -T \
    -o BatchMode=yes \
    -o ConnectTimeout=10 \
    -o StrictHostKeyChecking=yes \
    -i /root/.ssh/pve_to_openwrt_mgts_ed25519 \
    root@10.71.100.2 \
    'sh -s'" \
  >"$REMOTE_OUT" \
  2>"$SSH_ERR" <<'REMOTE'
set -u

TARGET="/root/hmn/hmn-refresh-pool-safe.sh"
LIB="/usr/local/lib/router-egress-vm101-runtime.sh"

hash_file() {
  sha256sum "$1" 2>/dev/null |
    awk '{print $1}'
}

echo "host=$(hostname)"
echo "date_utc=$(date -u +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || date)"
echo "kernel=$(uname -r)"

echo
echo "=== LIVE INSTALL STATE ==="

if [ -s "$TARGET" ]; then
  echo "target_present=true"
  echo "target_sha256=$(hash_file "$TARGET")"
  echo "target_bytes=$(wc -c < "$TARGET" | tr -d '[:space:]')"
else
  echo "target_present=false"
fi

if [ -e "$LIB" ]; then
  echo "runtime_library_present=true"
  echo "runtime_library_sha256=$(hash_file "$LIB")"
  echo "runtime_library_bytes=$(wc -c < "$LIB" | tr -d '[:space:]')"
else
  echo "runtime_library_present=false"
fi

echo
echo "=== FILESYSTEMS ==="
df -k 2>&1 || true

echo
echo "=== INODES ==="
df -i 2>&1 || true

echo
echo "=== MOUNTS ==="
mount 2>&1 || true

echo
echo "=== ROOT TOP LEVEL, KB ==="
du -k -d 1 / 2>/dev/null |
  sort -n |
  tail -n 30 ||
du -k /root /etc /usr /overlay /tmp 2>/dev/null |
  sort -n

echo
echo "=== OVERLAY TOP LEVEL, KB ==="
if [ -d /overlay ]; then
  du -k -d 2 /overlay 2>/dev/null |
    sort -n |
    tail -n 50 ||
  true
fi

echo
echo "=== ROOT HMM TOP LEVEL, KB ==="
if [ -d /root/hmn ]; then
  du -k -d 2 /root/hmn 2>/dev/null |
    sort -n |
    tail -n 60 ||
  true
fi

echo
echo "=== BACKUP DIRECTORIES ==="
if [ -d /root/hmn/backups ]; then
  find /root/hmn/backups \
    -mindepth 1 \
    -maxdepth 1 \
    -type d \
    -exec du -k -s {} \; 2>/dev/null |
  sort -n

  echo
  echo "backup_directory_count=$(
    find /root/hmn/backups \
      -mindepth 1 \
      -maxdepth 1 \
      -type d 2>/dev/null |
    wc -l |
    tr -d '[:space:]'
  )"
else
  echo "backups_directory_absent=true"
fi

echo
echo "=== LARGE OVERLAY FILES ==="
find /overlay /root /etc /usr/local \
  -xdev \
  -type f \
  -size +64k \
  -exec ls -ln {} \; 2>/dev/null |
sort -k5n |
tail -n 80 ||
true

echo
echo "=== TMP CAPACITY ==="
df -k /tmp 2>&1 || true
du -k -d 1 /tmp 2>/dev/null |
  sort -n |
  tail -n 30 ||
true

echo
echo "=== VPN HEALTH ==="
healthy=0
routes=0
slot=1

while [ "$slot" -le 5 ]; do
  iface="vpn$slot"
  table="$((200 + slot))"

  if ip route show table "$table" 2>/dev/null |
     grep -E "^default .*dev ${iface}([[:space:]]|$)" \
     >/dev/null
  then
    route_ok=true
    routes="$((routes + 1))"
  else
    route_ok=false
  fi

  probe_ok=false

  for ipaddr in 1.1.1.1 8.8.8.8 9.9.9.9; do
    if ping -I "$iface" -c 1 -W 2 "$ipaddr" \
         >/dev/null 2>&1
    then
      probe_ok=true
      break
    fi
  done

  if [ "$probe_ok" = "true" ]; then
    healthy="$((healthy + 1))"
  fi

  echo "${iface}_route_ok=$route_ok"
  echo "${iface}_healthy=$probe_ok"

  slot="$((slot + 1))"
done

echo "route_count=$routes"
echo "healthy_count=$healthy"

echo
echo "read_only=true"
echo "vm101_modified=false"
echo "installation_performed=false"
echo "cleanup_performed=false"
echo "refresh_ran=false"
echo "rebalance_ran=false"
REMOTE

SSH_RC=$?

python3 - \
  "$REPORT_DIR/facts.json" \
  "$REMOTE_OUT" \
  "$STEP" \
  "$SSH_RC" \
  "$TRYCF_REPORT" \
  "$REPORT_TXT" \
  "$FACTS_JSON" <<'PY'
import json
import re
import sys
from pathlib import Path

(
    output,
    audit_path,
    step,
    ssh_rc,
    report,
    report_txt,
    facts_json,
) = sys.argv[1:]

text = Path(audit_path).read_text(
    encoding="utf-8",
    errors="replace",
) if Path(audit_path).is_file() else ""

def last_value(key):
    matches = re.findall(
        rf"(?m)^{re.escape(key)}=(.*)$",
        text,
    )
    return matches[-1] if matches else None

def as_int(value):
    try:
        return int(value)
    except (TypeError, ValueError):
        return None

healthy = as_int(last_value("healthy_count"))
routes = as_int(last_value("route_count"))

data = {
    "schema": "router-step-facts-v1",
    "step": step,
    "assessment": {
        "decision": (
            f"PASS_{step}"
            if int(ssh_rc) == 0
            else f"STOP_{step}_SSH_FAILED"
        ),
        "step_execution": (
            "PASS" if int(ssh_rc) == 0 else "STOP"
        ),
        "operation_result":
            "VM101_STORAGE_AUDITED_READ_ONLY",
        "production_health": (
            "HEALTHY_5_OF_5"
            if healthy == 5 and routes == 5
            else "NOT_CONFIRMED_5_OF_5"
        ),
    },
    "live_state": {
        "target_present":
            last_value("target_present") == "true",
        "target_sha256":
            last_value("target_sha256"),
        "runtime_library_present":
            last_value("runtime_library_present") == "true",
    },
    "health": {
        "route_count": routes,
        "healthy_count": healthy,
    },
    "safety": {
        "read_only": True,
        "vm101_modified": False,
        "installation_performed": False,
        "cleanup_performed": False,
        "refresh_ran": False,
        "rebalance_ran": False,
    },
    "next_step":
        "SELECT_SAFE_STORAGE_REMEDIATION",
    "publish": {
        "trycf_report": report,
        "report_txt": report_txt,
        "facts_json": facts_json,
    },
}

Path(output).write_text(
    json.dumps(
        data,
        ensure_ascii=False,
        indent=2,
    ) + "\n",
    encoding="utf-8",
)
PY

if [ "$SSH_RC" -eq 0 ]; then
  DECISION="PASS_${STEP}"
else
  DECISION="STOP_${STEP}_SSH_FAILED"
fi

cat > "$REPORT_DIR/report.txt" <<EOF
=== ${STEP} RESULT ===
step=${STEP}
decision=${DECISION}
ssh_rc=${SSH_RC}
operation_result=VM101_STORAGE_AUDITED_READ_ONLY

$(cat "$REMOTE_OUT" 2>/dev/null)

next_step=SELECT_SAFE_STORAGE_REMEDIATION

TRYCF_REPORT=${TRYCF_REPORT}
REPORT_TXT=${REPORT_TXT}
FACTS_JSON=${FACTS_JSON}
EOF

cat > "$REPORT_DIR/index.html" <<EOF
<!doctype html>
<html lang="ru">
<head><meta charset="utf-8"><title>${STEP}</title></head>
<body style="font-family:system-ui;max-width:1100px;margin:40px auto">
<h1>${STEP}</h1>
<ul>
<li><a href="report.txt">report.txt</a></li>
<li><a href="facts.json">facts.json</a></li>
<li><a href="vm101-storage-audit.txt">vm101-storage-audit.txt</a></li>
<li><a href="ssh.stderr">ssh.stderr</a></li>
<li><a href="step.sh">step.sh</a></li>
</ul>
</body>
</html>
EOF

find "$REPORT_DIR" \
  -type f \
  ! -name SHA256SUMS \
  -print0 |
sort -z |
xargs -0 sha256sum \
  > "$REPORT_DIR/SHA256SUMS"

chmod -R a+rX "$REPORT_DIR"

echo "decision=$DECISION"
echo "ssh_rc=$SSH_RC"
echo "vm101_modified=false"
echo "cleanup_performed=false"
echo "installation_performed=false"

echo
echo "TRYCF_REPORT=$TRYCF_REPORT"
echo "REPORT_TXT=$REPORT_TXT"
echo "FACTS_JSON=$FACTS_JSON"

true
