#!/usr/bin/env bash
set -u

APP_DIR=/opt/wgtools
WG_ENV=/etc/wgtools/wgtools.env
HTTPS_ENV=/etc/wgtools/https.env
HTTPS_STATE=/etc/wgtools/https.json
VERSION_FILE="$APP_DIR/VERSION"
DATABASE_PATH="${WGTOOLS_DB:-/var/lib/wgtools/wgtools.db}"

if [[ ${EUID:-$(id -u)} -ne 0 ]]; then
  echo "Run wgtools as root (or with sudo)." >&2
  exit 1
fi

# shellcheck disable=SC1090
[[ -r "$WG_ENV" ]] && source "$WG_ENV"
# shellcheck disable=SC1090
[[ -r "$HTTPS_ENV" ]] && source "$HTTPS_ENV"

WG_INTERFACE="${WGTOOLS_INTERFACE:-wg0}"
NODE_INTERFACE="wgnode0"
HTTP_PORT="${WGTOOLS_PORT:-8341}"
HTTPS_ENABLED="${WGTOOLS_HTTPS_ENABLED:-0}"
HTTPS_PORT="${WGTOOLS_HTTPS_PORT:-443}"
ACCESS_PATH="${WGTOOLS_ACCESS_PATH:-}"
VERSION="$(cat "$VERSION_FILE" 2>/dev/null || echo unknown)"

if [[ -t 1 ]]; then
  BOLD='\033[1m'; DIM='\033[2m'; GREEN='\033[32m'; YELLOW='\033[33m'; RED='\033[31m'; CYAN='\033[36m'; HEADER_RED='\033[38;5;124m'; RESET='\033[0m'
else
  BOLD=''; DIM=''; GREEN=''; YELLOW=''; RED=''; CYAN=''; HEADER_RED=''; RESET=''
fi

service_state_raw() {
  local unit="$1"
  if systemctl is-active --quiet "$unit" 2>/dev/null; then
    printf 'Running'
  elif systemctl is-failed --quiet "$unit" 2>/dev/null; then
    printf 'Failed'
  else
    printf 'Stopped'
  fi
}

timer_state_raw() {
  local unit="$1"
  if systemctl is-active --quiet "$unit" 2>/dev/null; then
    printf 'Active'
  else
    printf 'Inactive'
  fi
}

state_color() {
  case "$1" in
    Running|Active|Enabled*) printf '%b' "$GREEN" ;;
    Failed) printf '%b' "$RED" ;;
    Stopped|Inactive|Disabled|"Not configured"|"Not installed") printf '%b' "$YELLOW" ;;
    *) printf '%b' "$RESET" ;;
  esac
}

https_target() {
  python3 - "$HTTPS_STATE" <<'PY' 2>/dev/null || true
import json,sys
from pathlib import Path
p=Path(sys.argv[1])
try:
    data=json.loads(p.read_text(encoding='utf-8'))
    print(str(data.get('target') or '').strip())
except Exception:
    pass
PY
}

primary_ip() {
  hostname -I 2>/dev/null | awk '{print $1}'
}

panel_url() {
  local host path
  if [[ "$HTTPS_ENABLED" == "1" ]]; then
    host="$(https_target)"
    [[ -z "$host" ]] && host="$(primary_ip)"
    [[ "$host" == *:* && "$host" != \[*\] ]] && host="[$host]"
    path="$ACCESS_PATH"
    [[ -n "$path" && "$path" != /* ]] && path="/$path"
    [[ -n "$path" && "$path" != */ ]] && path="$path/"
    if [[ "$HTTPS_PORT" == "443" ]]; then
      printf 'https://%s%s' "$host" "$path"
    else
      printf 'https://%s:%s%s' "$host" "$HTTPS_PORT" "$path"
    fi
  else
    host="$(primary_ip)"
    [[ "$host" == *:* && "$host" != \[*\] ]] && host="[$host]"
    printf 'http://%s:%s/' "$host" "$HTTP_PORT"
  fi
}

wireguard_interfaces() {
  {
    if [[ -d /etc/wireguard ]]; then
      for path in /etc/wireguard/*.conf; do
        [[ -e "$path" ]] || continue
        basename "$path" .conf
      done
    fi
    wg show interfaces 2>/dev/null | tr ' ' '\n' || true
  } | awk 'NF && $0 !~ /^wgrly/ && $0 !~ /^wgnode/ {print}' | sort -u
}

wg_state_for_raw() {
  local iface="$1"
  if wg show "$iface" >/dev/null 2>&1; then
    printf 'Running'
  elif [[ -f "/etc/wireguard/${iface}.conf" ]]; then
    printf 'Stopped'
  else
    printf 'Not configured'
  fi
}

node_state_raw() {
  if wg show "$NODE_INTERFACE" >/dev/null 2>&1; then
    printf 'Running'
  elif [[ -f "/etc/wireguard/${NODE_INTERFACE}.conf" ]]; then
    printf 'Stopped'
  else
    printf 'Not configured'
  fi
}

relay_agent_state_raw() {
  if systemctl is-active --quiet wgtools-relay-agent.service 2>/dev/null; then
    printf 'Running'
  elif [[ -e /etc/systemd/system/wgtools-relay-agent.service || -d /opt/wgtools-relay || -d /var/lib/wgtools-relay ]]; then
    printf 'Stopped'
  else
    printf 'Not installed'
  fi
}

cert_expiry() {
  local cert=/etc/letsencrypt/live/wgtools/fullchain.pem
  [[ -r "$cert" ]] || { printf '—'; return; }
  openssl x509 -in "$cert" -noout -enddate 2>/dev/null | sed 's/^notAfter=//' || printf '—'
}

print_row() {
  local label="$1" value="$2" color="${3:-$RESET}"
  printf '│ %-22s │ %b%-38s%b │\n' "$label" "$color" "$value" "$RESET"
}

print_status() {
  HTTPS_ENABLED="${WGTOOLS_HTTPS_ENABLED:-$HTTPS_ENABLED}"
  HTTPS_PORT="${WGTOOLS_HTTPS_PORT:-$HTTPS_PORT}"
  ACCESS_PATH="${WGTOOLS_ACCESS_PATH:-$ACCESS_PATH}"
  [[ -t 1 ]] && printf '\033c' 2>/dev/null || true

  printf '┌─────────────────────────────────────────────────────────────────┐\n'
  printf '│ %bWGTools Management%b - v%-41s │\n' "$BOLD" "$RESET" "$VERSION"
  printf '├────────────────────────┬────────────────────────────────────────┤\n'

  local value color iface
  value="$(service_state_raw wgtools.service)"; color="$(state_color "$value")"; print_row 'Panel service' "$value" "$color"

  mapfile -t wg_ifaces < <(wireguard_interfaces)
  if [[ ${#wg_ifaces[@]} -eq 0 ]]; then
    value='Not configured'; color="$(state_color "$value")"; print_row 'WireGuard' "$value" "$color"
  else
    for iface in "${wg_ifaces[@]}"; do
      value="$(wg_state_for_raw "$iface")"; color="$(state_color "$value")"; print_row "WireGuard $iface" "$value" "$color"
    done
  fi

  value="$(node_state_raw)"; color="$(state_color "$value")"; print_row 'Nodes tunnel' "$value" "$color"
  value="$(service_state_raw wgtools-telegram.service)"; color="$(state_color "$value")"; print_row 'Telegram service' "$value" "$color"
  value="$(timer_state_raw wgtools-expiry.timer)"; color="$(state_color "$value")"; print_row 'Expiry timer' "$value" "$color"

  if [[ "$HTTPS_ENABLED" == "1" ]]; then
    value="Enabled - TCP $HTTPS_PORT"; print_row 'HTTPS' "$value" "$GREEN"
    value="$(timer_state_raw wgtools-certbot-renew.timer)"; color="$(state_color "$value")"; print_row 'Renewal timer' "$value" "$color"
    print_row 'Panel path' "${ACCESS_PATH:-—}" "$CYAN"
    print_row 'Certificate until' "$(cert_expiry)" "$RESET"
  else
    print_row 'HTTPS' 'Disabled' "$YELLOW"
  fi

  if [[ -e /etc/systemd/system/wgtools-relay-agent.service || -d /opt/wgtools-relay || -d /var/lib/wgtools-relay ]]; then
    value="$(relay_agent_state_raw)"; color="$(state_color "$value")"; print_row 'Relay agent (local)' "$value" "$color"
  fi

  printf '└────────────────────────┴────────────────────────────────────────┘\n'
  printf '%bPanel URL:%b %b%s%b\n' "$BOLD" "$RESET" "$CYAN" "$(panel_url)" "$RESET"
}

format_age() {
  local epoch="${1:-0}" now delta
  [[ "$epoch" =~ ^[0-9]+$ ]] || { printf 'never'; return; }
  (( epoch > 0 )) || { printf 'never'; return; }
  now="$(date +%s)"
  delta=$(( now - epoch ))
  (( delta < 0 )) && delta=0
  if (( delta < 60 )); then
    printf '%ss ago' "$delta"
  elif (( delta < 3600 )); then
    printf '%sm ago' "$((delta / 60))"
  elif (( delta < 86400 )); then
    printf '%sh ago' "$((delta / 3600))"
  else
    printf '%sd ago' "$((delta / 86400))"
  fi
}

online_threshold_seconds() {
  python3 - "$DATABASE_PATH" "${WGTOOLS_ONLINE_THRESHOLD_SECONDS:-180}" <<'PYTHRESH' 2>/dev/null || printf '180'
import sqlite3, sys
path, default = sys.argv[1], sys.argv[2]
try:
    fallback = max(30, min(int(default), 3600))
except Exception:
    fallback = 180
try:
    conn = sqlite3.connect(path)
    row = conn.execute("SELECT value FROM app_settings WHERE key='online_threshold_seconds'").fetchone()
    conn.close()
    value = int(row[0]) if row else fallback
    print(max(30, min(value, 3600)))
except Exception:
    print(fallback)
PYTHRESH
}

show_wireguard_status() {
  local requested="${1:-}" iface snapshot threshold
  mapfile -t interfaces < <(wireguard_interfaces)
  if [[ -n "$requested" ]]; then
    interfaces=("$requested")
  fi
  if [[ ${#interfaces[@]} -eq 0 ]]; then
    echo "No WireGuard interfaces are configured."
    return 1
  fi

  threshold="$(online_threshold_seconds)"
  [[ "$threshold" =~ ^[0-9]+$ ]] || threshold=180

  echo
  printf '%bWireGuard status%b\n' "$BOLD" "$RESET"

  for iface in "${interfaces[@]}"; do
    if [[ ! -f "/etc/wireguard/${iface}.conf" ]] && ! wg show "$iface" >/dev/null 2>&1; then
      printf '\n%s: Not found\n' "$iface"
      continue
    fi

    snapshot=''
    if [[ -x /usr/local/libexec/wgtools-helper ]]; then
      snapshot="$(printf '%s\n' '{"view":"clients"}' | /usr/local/libexec/wgtools-helper snapshot "$iface" 2>/dev/null || true)"
    fi

    if [[ -n "$snapshot" ]]; then
      python3 - "$iface" "$threshold" "$DATABASE_PATH" 3<<<"$snapshot" <<'PYSTATUS'
import json, sqlite3, sys, time

iface = sys.argv[1]
database_path = sys.argv[3]
try:
    threshold = max(30, min(int(sys.argv[2]), 3600))
except Exception:
    threshold = 180

try:
    data = json.loads(open('/dev/fd/3', encoding='utf-8').read())
except Exception:
    data = {}

if not isinstance(data, dict) or not data.get('ok'):
    raise SystemExit(2)

now = int(time.time())
peers = list(data.get('peers') or [])
running = bool(data.get('running'))
config = data.get('config') or {}
interface = config.get('interface') or {}
address = str(interface.get('address') or '—')
port = data.get('listen_port') or interface.get('listen_port') or '—'

audit = {}
try:
    conn = sqlite3.connect(database_path)
    rows = conn.execute(
        'SELECT public_key,latest_handshake,endpoint FROM audit_wg_connection_state WHERE interface=?',
        (iface,),
    ).fetchall()
    conn.close()
    audit = {str(row[0]): {'latest_handshake': int(row[1] or 0), 'endpoint': str(row[2] or '')} for row in rows}
except Exception:
    audit = {}


def handshake_epoch(peer):
    try:
        live = int(peer.get('latest_handshake') or 0)
    except Exception:
        live = 0
    saved = audit.get(str(peer.get('public_key') or ''), {})
    try:
        historical = int(saved.get('latest_handshake') or 0)
    except Exception:
        historical = 0
    return max(live, historical)


def peer_endpoint(peer):
    value = str(peer.get('endpoint') or '').strip()
    if value:
        return value
    return str(audit.get(str(peer.get('public_key') or ''), {}).get('endpoint') or '—')


def age(epoch):
    try:
        epoch = int(epoch or 0)
    except Exception:
        epoch = 0
    if epoch <= 0:
        return 'Never'
    delta = max(0, now - epoch)
    if delta < 60:
        return f'{delta}s ago'
    if delta < 3600:
        return f'{delta // 60}m ago'
    if delta < 86400:
        return f'{delta // 3600}h ago'
    return f'{delta // 86400}d ago'


def online(peer):
    hs = handshake_epoch(peer)
    return bool(running and hs > 0 and now - hs <= threshold)


def human_bytes(value):
    try:
        n = float(int(value or 0))
    except Exception:
        n = 0.0
    units = ['B', 'KiB', 'MiB', 'GiB', 'TiB']
    idx = 0
    while n >= 1024 and idx < len(units) - 1:
        n /= 1024.0
        idx += 1
    if idx == 0:
        return f'{int(n)} {units[idx]}'
    if n >= 100:
        return f'{n:.0f} {units[idx]}'
    if n >= 10:
        return f'{n:.1f} {units[idx]}'
    return f'{n:.2f} {units[idx]}'


def short_key(value):
    value = str(value or '')
    if len(value) <= 16:
        return value or 'Unnamed peer'
    return value[:8] + '…' + value[-6:]

def compact_bytes(value):
    try:
        n = float(int(value or 0))
    except Exception:
        n = 0.0
    units = ['B', 'K', 'M', 'G', 'T']
    idx = 0
    while n >= 1024 and idx < len(units) - 1:
        n /= 1024.0
        idx += 1
    if idx == 0:
        return f'{int(n)}B'
    if n >= 100:
        return f'{n:.0f}{units[idx]}'
    if n >= 10:
        return f'{n:.1f}{units[idx]}'
    return f'{n:.2f}{units[idx]}'


def fit(value, width, middle=False):
    value = str(value or '-')
    if len(value) <= width:
        return value
    if width <= 3:
        return value[:width]
    if middle:
        right = min(6, max(2, width // 2))
        left = width - right - 1
        return value[:left] + '~' + value[-right:]
    return value[:width - 1] + '~'


online_count = sum(1 for p in peers if online(p))
state = 'Running' if running else 'Stopped'
print()
print(f'{iface}  {state}  {address}  UDP {port}  Peers {len(peers)} ({online_count} online)')

if not peers:
    print('Clients / peers: none configured')
    raise SystemExit(0)

# Keep one peer per line, but do not shorten Endpoint: the terminal usually has
# more horizontal room than the boxed menu. Column widths adapt to current data.
rows = []
for peer in peers:
    name = str(peer.get('name') or '').strip()
    if not name or name.lower() == 'unnamed peer':
        name = short_key(peer.get('public_key'))
    allowed = list(peer.get('allowed_ips') or peer.get('allowed_ips_runtime') or [])
    vpn_ip = str(peer.get('vpn_address') or (allowed[0] if allowed else '-'))
    peer_state = 'Online' if online(peer) else 'Offline'
    handshake = age(handshake_epoch(peer))
    endpoint = peer_endpoint(peer)
    if endpoint in {'—', '(none)', 'None', ''}:
        endpoint = '-'
    traffic = f"{compact_bytes(peer.get('rx_bytes'))}/{compact_bytes(peer.get('tx_bytes'))}"
    rows.append((name, vpn_ip, peer_state, handshake, endpoint, traffic))

name_width = min(20, max([len('Name')] + [len(r[0]) for r in rows]))
vpn_width = max([len('VPN IP')] + [len(r[1]) for r in rows])
state_width = max([len('State')] + [len(r[2]) for r in rows])
handshake_width = max([len('Handshake')] + [len(r[3]) for r in rows])
endpoint_width = max([len('Endpoint')] + [len(r[4]) for r in rows])
traffic_width = max([len('RX/TX')] + [len(r[5]) for r in rows])

print()
print('Clients / peers')
header = (
    f"{'Name':<{name_width}} "
    f"{'VPN IP':<{vpn_width}} "
    f"{'State':<{state_width}} "
    f"{'Handshake':<{handshake_width}} "
    f"{'Endpoint':<{endpoint_width}} "
    f"{'RX/TX':<{traffic_width}}"
)
print(header)
print('-' * len(header))
for name, vpn_ip, peer_state, handshake, endpoint, traffic in rows:
    print(
        f"{fit(name, name_width):<{name_width}} "
        f"{vpn_ip:<{vpn_width}} "
        f"{peer_state:<{state_width}} "
        f"{handshake:<{handshake_width}} "
        f"{endpoint:<{endpoint_width}} "
        f"{traffic:<{traffic_width}}"
    )
PYSTATUS
      rc=$?
      [[ $rc -eq 0 ]] && continue
    fi

    # Fallback for a damaged/missing helper: still show live WireGuard data.
    local state address port peers latest latest_text
    state="$(wg_state_for_raw "$iface")"
    address="$(ip -o -4 addr show dev "$iface" 2>/dev/null | awk '{print $4}' | paste -sd, -)"
    [[ -n "$address" ]] || address='—'
    if wg show "$iface" >/dev/null 2>&1; then
      port="$(wg show "$iface" listen-port 2>/dev/null || true)"
      [[ "$port" =~ ^[0-9]+$ ]] || port='—'
      peers="$(wg show "$iface" peers 2>/dev/null | awk 'NF{n++} END{print n+0}')"
      latest="$(wg show "$iface" latest-handshakes 2>/dev/null | awk '$2>m{m=$2} END{print m+0}')"
      latest_text="$(format_age "$latest")"
    else
      port='—'; peers='0'; latest_text='—'
    fi
    printf '\nInterface: %s\n  State: %s\n  Address: %s\n  Port: %s\n  Peers: %s\n  Latest handshake: %s\n' \
      "$iface" "$state" "$address" "$port" "$peers" "$latest_text"
  done
}

control_wireguard() {
  local action="$1" requested="${2:-}" iface
  mapfile -t interfaces < <(wireguard_interfaces)
  if [[ -n "$requested" ]]; then
    iface="$requested"
    if [[ ! -f "/etc/wireguard/${iface}.conf" ]]; then
      echo "WireGuard interface $iface is not configured."
      return 1
    fi
  else
    if [[ ${#interfaces[@]} -eq 0 ]]; then
      echo "No WireGuard interfaces are configured."
      return 1
    elif [[ ${#interfaces[@]} -eq 1 ]]; then
      iface="${interfaces[0]}"
    elif [[ -f "/etc/wireguard/${WG_INTERFACE}.conf" ]]; then
      iface="$WG_INTERFACE"
    else
      echo "Multiple WireGuard interfaces are configured: ${interfaces[*]}"
      echo "Use: wgtools ${action}-wg <interface>"
      return 1
    fi
  fi

  case "$action" in
    start|stop|restart) systemctl "$action" "wg-quick@${iface}.service" ;;
    *) echo "Unsupported WireGuard action: $action" >&2; return 1 ;;
  esac
}

menu_wireguard_action() {
  local action="$1" selected
  mapfile -t _wg_menu_ifaces < <(wireguard_interfaces)
  if [[ ${#_wg_menu_ifaces[@]} -eq 0 ]]; then
    echo "No WireGuard interfaces are configured."
    return 1
  fi
  if [[ ${#_wg_menu_ifaces[@]} -eq 1 ]]; then
    control_wireguard "$action" "${_wg_menu_ifaces[0]}"
    return
  fi
  printf 'Interface [%s]: ' "${_wg_menu_ifaces[*]}"
  read -r selected
  [[ -n "$selected" ]] || { echo "Cancelled."; return 0; }
  control_wireguard "$action" "$selected"
}

disable_https_rescue() {
  if [[ "$HTTPS_ENABLED" != "1" ]]; then
    echo "Built-in HTTPS is already disabled."
    return 0
  fi
  printf 'Disable built-in HTTPS and restore HTTP on TCP %s? [y/N] ' "$HTTP_PORT"
  read -r answer
  [[ "$answer" =~ ^[Yy]$ ]] || return 0
  if [[ -x /usr/local/libexec/wgtools-helper ]]; then
    /usr/local/libexec/wgtools-helper https_disable "$WG_INTERFACE" >/tmp/wgtools-cli-https.json 2>/tmp/wgtools-cli-https.err || {
      cat /tmp/wgtools-cli-https.err >&2 || true
      rm -f /tmp/wgtools-cli-https.json /tmp/wgtools-cli-https.err
      return 1
    }
    rm -f /tmp/wgtools-cli-https.json /tmp/wgtools-cli-https.err
    sleep 6
    # shellcheck disable=SC1090
    [[ -r "$HTTPS_ENV" ]] && source "$HTTPS_ENV"
    HTTPS_ENABLED="${WGTOOLS_HTTPS_ENABLED:-0}"
    echo "HTTP restored: $(panel_url)"
  else
    echo "WGTools helper is not installed." >&2
    return 1
  fi
}

mfa_enabled_users() {
  python3 - "$DATABASE_PATH" <<'PYMFAUSERS' 2>/dev/null || true
import sqlite3, sys
path=sys.argv[1]
try:
    conn=sqlite3.connect(path)
    cols={row[1] for row in conn.execute("PRAGMA table_info(users)")}
    if "mfa_enabled" not in cols:
        raise SystemExit(0)
    for row in conn.execute("SELECT username FROM users WHERE mfa_enabled=1 ORDER BY username COLLATE NOCASE"):
        print(str(row[0]))
except Exception:
    pass
PYMFAUSERS
}

disable_mfa_cli() {
  local requested="${1:-}" selected answer i
  mapfile -t _mfa_users < <(mfa_enabled_users)
  if [[ ${#_mfa_users[@]} -eq 0 ]]; then
    echo "MFA is not enabled for any WGTools user."
    return 0
  fi

  if [[ -n "$requested" ]]; then
    selected=''
    for i in "${_mfa_users[@]}"; do
      if [[ "${i,,}" == "${requested,,}" ]]; then selected="$i"; break; fi
    done
    if [[ -z "$selected" ]]; then
      echo "MFA-enabled user not found: $requested" >&2
      return 1
    fi
  elif [[ ${#_mfa_users[@]} -eq 1 ]]; then
    selected="${_mfa_users[0]}"
  else
    echo "MFA-enabled users:"
    for i in "${!_mfa_users[@]}"; do printf '  %d. %s\n' "$((i+1))" "${_mfa_users[$i]}"; done
    printf 'Select user [1-%d]: ' "${#_mfa_users[@]}"
    read -r answer
    [[ "$answer" =~ ^[0-9]+$ ]] || { echo "Cancelled."; return 0; }
    (( answer >= 1 && answer <= ${#_mfa_users[@]} )) || { echo "Cancelled."; return 0; }
    selected="${_mfa_users[$((answer-1))]}"
  fi

  printf 'Disable MFA for %b%s%b? This invalidates existing sessions. [y/N] ' "$BOLD" "$selected" "$RESET"
  read -r answer
  [[ "$answer" =~ ^[Yy]$ ]] || { echo "Cancelled."; return 0; }

  python3 - "$DATABASE_PATH" "$selected" <<'PYMFADISABLE'
import json, sqlite3, sys, time
path, username = sys.argv[1], sys.argv[2]
conn=sqlite3.connect(path)
try:
    cols={row[1] for row in conn.execute("PRAGMA table_info(users)")}
    required={"mfa_enabled","mfa_secret","mfa_recovery_codes","mfa_confirmed_at","session_version"}
    if not required.issubset(cols):
        raise SystemExit("This WGTools database does not support MFA.")
    row=conn.execute("SELECT id,mfa_enabled FROM users WHERE username=? COLLATE NOCASE",(username,)).fetchone()
    if not row:
        raise SystemExit("User not found.")
    if not int(row[1] or 0):
        print("MFA is already disabled.")
        raise SystemExit(0)
    conn.execute(
        "UPDATE users SET mfa_enabled=0,mfa_secret='',mfa_recovery_codes='[]',mfa_confirmed_at=0,session_version=session_version+1 WHERE id=?",
        (int(row[0]),),
    )
    audit_exists=conn.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='audit_log'").fetchone()
    if audit_exists:
        conn.execute(
            "INSERT INTO audit_log(created_at,username,action,object,result,details) VALUES(?,?,?,?,?,?)",
            (int(time.time()),"root-cli","user.mfa_disabled_cli",username,"disabled",json.dumps({"reason":"root CLI rescue"},separators=(",",":"))),
        )
    conn.commit()
    print(f"MFA disabled for {username}. Existing web sessions were invalidated.")
finally:
    conn.close()
PYMFADISABLE
}

show_logs() {
  echo "Press Ctrl+C to return."
  journalctl -u wgtools.service -f --no-pager
}

show_bot_logs() {
  echo "Press Ctrl+C to return."
  journalctl -u wgtools-telegram.service -f --no-pager
}

uninstall_wgtools() {
  echo
  printf '%bUninstall WGTools from this host?%b\n' "$YELLOW" "$RESET"
  cat <<'TXT'
This removes the WGTools application, web/Telegram/timer services, CLI,
internal Nodes tunnel and local Relay-home transport services.

Preserved intentionally:
  • normal WireGuard interfaces/configs and packages
  • /var/lib/wgtools (database, backups and reusable state)
  • Let's Encrypt certificates
  • Relay Agents/tenants on other VPS hosts
TXT
  printf '\nType %bUNINSTALL%b to continue: ' "$BOLD" "$RESET"
  read -r answer
  [[ "$answer" == "UNINSTALL" ]] || { echo "Cancelled."; return 0; }
  if [[ -x "$APP_DIR/scripts/uninstall.sh" ]]; then
    bash "$APP_DIR/scripts/uninstall.sh"
  else
    echo "Uninstall script was not found: $APP_DIR/scripts/uninstall.sh" >&2
    return 1
  fi
  exit 0
}

full_cleanup() {
  echo
  printf '%bFULL CLEANUP — destructive operation%b\n' "$RED$BOLD" "$RESET"
  cat <<'TXT'
This wipes this host's WGTools installation completely:
  • WGTools application, services, database, backups and CLI
  • Nodes and local Relay Agent/tenant state on THIS host
  • all WireGuard interfaces and /etc/wireguard configs on THIS host
  • WGTools Let's Encrypt certificate
  • Debian wireguard / wireguard-tools packages

Remote Relay Agents on OTHER VPS hosts are not contacted or deleted.
Generic shared OS tools such as iproute2, iptables, Python and certbot are kept.
TXT
  printf '\nType %bDELETE ALL%b to continue: ' "$RED$BOLD" "$RESET"
  read -r answer
  [[ "$answer" == "DELETE ALL" ]] || { echo "Cancelled."; return 0; }
  if [[ -x "$APP_DIR/scripts/full-clean.sh" ]]; then
    WGTOOLS_FULL_CLEAN_CONFIRMED=1 bash "$APP_DIR/scripts/full-clean.sh"
  else
    echo "Full cleanup script was not found: $APP_DIR/scripts/full-clean.sh" >&2
    return 1
  fi
  exit 0
}

run_action() {
  case "${1:-}" in
    status) print_status ;;
    start) systemctl start wgtools.service ;;
    stop) systemctl stop wgtools.service ;;
    restart) systemctl restart wgtools.service ;;
    status-wg) show_wireguard_status "${2:-}" ;;
    start-wg) control_wireguard start "${2:-}" ;;
    stop-wg) control_wireguard stop "${2:-}" ;;
    restart-wg) control_wireguard restart "${2:-}" ;;
    logs) journalctl -u wgtools.service -n 80 --no-pager ;;
    bot-logs) journalctl -u wgtools-telegram.service -n 80 --no-pager ;;
    http-rescue) disable_https_rescue ;;
    disable-mfa) disable_mfa_cli "${2:-}" ;;
    uninstall) uninstall_wgtools ;;
    full-clean) full_cleanup ;;
    *) return 2 ;;
  esac
}

if [[ $# -gt 0 ]]; then
  run_action "$@" || {
    rc=$?
    if [[ $rc -eq 2 ]]; then
      echo "Usage: wgtools [status|start|stop|restart|status-wg [interface]|start-wg [interface]|stop-wg [interface]|restart-wg [interface]|logs|bot-logs|http-rescue|disable-mfa [username]|uninstall|full-clean]" >&2
    fi
    exit "$rc"
  }
  exit 0
fi

while true; do
  # Reload mutable HTTPS settings on each pass.
  unset WGTOOLS_HTTPS_ENABLED WGTOOLS_HTTPS_PORT WGTOOLS_ACCESS_PATH 2>/dev/null || true
  # shellcheck disable=SC1090
  [[ -r "$HTTPS_ENV" ]] && source "$HTTPS_ENV"
  HTTPS_ENABLED="${WGTOOLS_HTTPS_ENABLED:-0}"
  HTTPS_PORT="${WGTOOLS_HTTPS_PORT:-443}"
  ACCESS_PATH="${WGTOOLS_ACCESS_PATH:-}"
  print_status
  printf '\n┌─────────────────────────────────────────────────────────────────┐\n'
  printf '│ %b%-63s%b │\n' "$HEADER_RED$BOLD" 'Panel' "$RESET"
  printf '│ %-63s │\n' ' 1. Refresh status'
  printf '│ %-63s │\n' ' 2. Start'
  printf '│ %-63s │\n' ' 3. Stop'
  printf '│ %-63s │\n' ' 4. Restart'
  printf '├─────────────────────────────────────────────────────────────────┤\n'
  printf '│ %b%-63s%b │\n' "$HEADER_RED$BOLD" 'WireGuard' "$RESET"
  printf '│ %-63s │\n' ' 5. Status'
  printf '│ %-63s │\n' ' 6. Start'
  printf '│ %-63s │\n' ' 7. Stop'
  printf '│ %-63s │\n' ' 8. Restart'
  printf '├─────────────────────────────────────────────────────────────────┤\n'
  printf '│ %b%-63s%b │\n' "$HEADER_RED$BOLD" 'Logs & recovery' "$RESET"
  printf '│ %-63s │\n' ' 9. WGTools logs'
  printf '│ %-63s │\n' '10. Telegram logs'
  printf '│ %-63s │\n' '11. Restore HTTP access (disable built-in HTTPS)'
  printf '├─────────────────────────────────────────────────────────────────┤\n'
  printf '│ %b%-63s%b │\n' "$HEADER_RED$BOLD" 'Security' "$RESET"
  printf '│ %-63s │\n' '12. Disable user MFA (emergency rescue)'
  printf '├─────────────────────────────────────────────────────────────────┤\n'
  printf '│ %b%-63s%b │\n' "$HEADER_RED$BOLD" 'Removal' "$RESET"
  printf '│ %-63s │\n' '13. Uninstall WGTools (keep WireGuard + reusable data)'
  printf '│ %-63s │\n' '14. FULL CLEANUP (WGTools + WireGuard + Relay + all data)'
  printf '├─────────────────────────────────────────────────────────────────┤\n'
  printf '│ %-63s │\n' ' 0. Exit'
  printf '└─────────────────────────────────────────────────────────────────┘\n'
  printf '\nSelect [0-14]: '
  read -r choice || exit 0
  case "$choice" in
    1) ;;
    2) systemctl start wgtools.service; sleep 1 ;;
    3) systemctl stop wgtools.service; sleep 1 ;;
    4) systemctl restart wgtools.service; sleep 1 ;;
    5) show_wireguard_status || true; printf '\nPress Enter to continue...'; read -r _ ;;
    6) menu_wireguard_action start || true; sleep 1 ;;
    7) menu_wireguard_action stop || true; sleep 1 ;;
    8) menu_wireguard_action restart || true; sleep 1 ;;
    9) show_logs || true ;;
    10) show_bot_logs || true ;;
    11) disable_https_rescue || true; printf '\nPress Enter to continue...'; read -r _ ;;
    12) disable_mfa_cli || true; printf '\nPress Enter to continue...'; read -r _ ;;
    13) uninstall_wgtools || true; printf '\nPress Enter to continue...'; read -r _ ;;
    14) full_cleanup || true; printf '\nPress Enter to continue...'; read -r _ ;;
    0) exit 0 ;;
    *) printf 'Unknown selection.\n'; sleep 1 ;;
  esac
done
