#!/bin/bash
# Install the proxylab "pool + urltest + watchdog" stack.
# Safe by design: everything is backed up, and the old unit is restored if the
# new config fails validation.
set -uo pipefail

SRC=$(cd "$(dirname "$0")" && pwd)
TS=$(date +%Y%m%d-%H%M%S)
BK="/root/proxylab-backup-$TS"
PY=/usr/bin/python3
RUNUSER=/usr/sbin/runuser

say() { printf '\n### %s\n' "$*"; }

say "1/7 backup -> $BK"
mkdir -p "$BK"
for f in /etc/systemd/system/proxylab-serve.service \
         /etc/systemd/system/proxylab.timer \
         /opt/proxy-lab/data/serve.json \
         /usr/local/etc/xray/config.json \
         /etc/privoxy/config; do
  [ -e "$f" ] && cp -a "$f" "$BK/$(echo "$f" | tr '/' '_')"
done
ls -1 "$BK"

say "2/7 install files"
install -o root -g proxylab -m 750 "$SRC/render.py"  /opt/proxy-lab/render.py
install -o root -g root     -m 755 "$SRC/cycle.sh"   /opt/proxy-lab/cycle.sh
install -o root -g root     -m 755 "$SRC/watchdog.sh" /opt/proxy-lab/watchdog.sh
install -m 644 "$SRC/proxylab-serve.service"    /etc/systemd/system/proxylab-serve.service
install -m 644 "$SRC/proxylab-cycle.service"    /etc/systemd/system/proxylab-cycle.service
install -m 644 "$SRC/proxylab-cycle.timer"      /etc/systemd/system/proxylab-cycle.timer
install -m 644 "$SRC/proxylab-watchdog.service" /etc/systemd/system/proxylab-watchdog.service
install -m 644 "$SRC/proxylab-watchdog.timer"   /etc/systemd/system/proxylab-watchdog.timer
cat >/etc/logrotate.d/proxylab <<'EOF'
/var/log/proxylab-cycle.log /var/log/proxylab-watchdog.log {
    weekly
    rotate 4
    compress
    missingok
    notifempty
    copytruncate
}
EOF
touch /var/log/proxylab-cycle.log /var/log/proxylab-watchdog.log
chmod 640 /var/log/proxylab-cycle.log /var/log/proxylab-watchdog.log
systemctl daemon-reload

say "3/7 render config from current pool"
if ! "$RUNUSER" -u proxylab -- "$PY" /opt/proxy-lab/render.py; then
  echo "!! render failed -> restoring the previous unit and config"
  cp -a "$BK/_etc_systemd_system_proxylab-serve.service" /etc/systemd/system/proxylab-serve.service 2>/dev/null
  systemctl daemon-reload
  exit 1
fi
"$PY" - "$BK" <<'PY'
import json,sys,os
cfg=json.load(open('/opt/proxy-lab/data/serve.json'))
print('  inbounds:', [(i['listen'], i['listen_port']) for i in cfg['inbounds']])
print('  outbounds:', len(cfg['outbounds'])-1, 'urltest group:', cfg['outbounds'][-1]['tag'])
PY

say "4/7 switch serve unit to sing-box"
systemctl stop proxylab-serve.service 2>/dev/null
systemctl start proxylab-serve.service
sleep 6
systemctl is-active proxylab-serve.service
ss -tlnp 2>/dev/null | grep ':20808' | sed 's/  */ /g'

say "5/7 end-to-end probe"
for addr in 127.0.0.1 172.19.0.1 172.17.0.1; do
  code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 10 -x "http://$addr:20808" https://www.gstatic.com/generate_204 2>/dev/null)
  printf '  via %-11s -> %s\n' "$addr" "${code:-000}"
done

say "6/7 retarget timers"
systemctl disable --now proxylab.timer 2>/dev/null || true
systemctl enable --now proxylab-cycle.timer proxylab-watchdog.timer 2>/dev/null
systemctl list-timers proxylab-cycle.timer proxylab-watchdog.timer --no-pager 2>/dev/null

say "7/7 close open proxy listeners (guarded)"
"$PY" - <<'PY'
import json,json as j,os,shutil,subprocess,sys
# --- xray: only rebind if nobody remote is connected
out=subprocess.run(["ss","-tn","state","established"],capture_output=True,text=True).stdout
remote=[l for l in out.splitlines() if (':10808' in l or ':10809' in l) and '127.0.0.1' not in l]
if remote:
    print(f"  xray: {len(remote)} non-local client(s) connected -> SKIP rebind")
else:
    p='/usr/local/etc/xray/config.json'
    cfg=j.load(open(p)); changed=False
    for ib in cfg.get('inbounds',[]):
        if ib.get('listen')=='0.0.0.0':
            ib['listen']='127.0.0.1'; changed=True
    if changed:
        shutil.copy2(p,p+'.prebind')
        j.dump(cfg,open(p,'w'),indent=2)
        t=subprocess.run(['/usr/local/bin/xray','-test','-c',p],capture_output=True,text=True)
        if t.returncode==0:
            subprocess.run(['systemctl','restart','xray'],check=False)
            print("  xray: rebound to 127.0.0.1 and restarted")
        else:
            shutil.copy2(p+'.prebind',p)
            print("  xray: test failed, reverted ->",(t.stderr or t.stdout)[:200])
    else:
        print("  xray: no 0.0.0.0 inbound found")
PY

if grep -q '^listen-address  0.0.0.0:8118' /etc/privoxy/config 2>/dev/null; then
  if ss -tn state established 2>/dev/null | grep -q ':8118'; then
    echo "  privoxy: active clients present -> SKIP rebind"
  else
    sed -i 's|^listen-address  0.0.0.0:8118|listen-address  127.0.0.1:8118|' /etc/privoxy/config
    systemctl restart privoxy && echo "  privoxy: rebound to 127.0.0.1"
  fi
fi

say "RESULT"
systemctl is-active proxylab-serve.service proxylab-cycle.timer proxylab-watchdog.timer xray privoxy apache2 mysql
ss -tlnp 2>/dev/null | grep -E ':(10808|10809|20808|8118)\s' | sed 's/  */ /g' | cut -c1-95
echo "backup: $BK"
