#!/usr/bin/env bash
set -euo pipefail

CONF=/opt/apusic-real/runtime/amdc-poc.yaml
AMDC=/opt/apusic-real/install/amdc
PASS='AMDC@Kbt2026#6359'

python3 - <<'PY'
from pathlib import Path
p = Path("/opt/apusic-real/runtime/amdc-poc.yaml")
s = p.read_text()
s = s.replace('    bind:\n        - "127.0.0.1"\n        - "-::1"', '    bind:\n        - "0.0.0.0"')
s = s.replace('    requirepass: ""', '    requirepass: "AMDC@Kbt2026#6359"')
p.write_text(s)
PY

if [ -f /opt/apusic-real/runtime/amdc.pid ]; then
  kill "$(cat /opt/apusic-real/runtime/amdc.pid)" 2>/dev/null || true
fi
pkill -f "amdc-server.*6359" 2>/dev/null || true
sleep 1

cd "$AMDC"
./amdc-server "$CONF" > /opt/apusic-real/logs/amdc-start.log 2>&1 || {
  cat /opt/apusic-real/logs/amdc-start.log
  exit 1
}
sleep 1

echo "== listen =="
ss -lntp | grep 6359 || true
echo "== unauth =="
"$AMDC/amdc-cli" -h 127.0.0.1 -p 6359 ping || true
echo "== auth =="
"$AMDC/amdc-cli" -h 127.0.0.1 -p 6359 -a "$PASS" ping
echo "== firewall =="
systemctl is-active firewalld 2>/dev/null || true
iptables -S INPUT 2>/dev/null | sed -n "1,30p" || true
