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

install -d -m 0755 /opt/avnm-proof

cat >/opt/avnm-proof/server.py <<'PY'
import socket
import threading


def serve(port):
    sock = socket.socket()
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind(("0.0.0.0", port))
    sock.listen(20)
    while True:
        client, _ = sock.accept()
        client.sendall((f"AVNM workshop proof port {port}\n").encode())
        client.close()


for proof_port in (8080, 8443):
    threading.Thread(target=serve, args=(proof_port,), daemon=True).start()

threading.Event().wait()
PY

cat >/etc/systemd/system/avnm-proof.service <<'UNIT'
[Unit]
Description=Azure Workshopz AVNM proof listeners
After=network-online.target

[Service]
ExecStart=/usr/bin/python3 /opt/avnm-proof/server.py
Restart=always

[Install]
WantedBy=multi-user.target
UNIT

systemctl daemon-reload
systemctl enable --now avnm-proof.service

for attempt in $(seq 1 30); do
    if systemctl is-active --quiet avnm-proof.service \
        && ss -lnt | grep -q ':8080' \
        && ss -lnt | grep -q ':8443'; then
        echo 'EDGE_PROOF_SERVICE=ACTIVE PORTS=8080,8443'
        exit 0
    fi
    sleep 1
done

systemctl status avnm-proof.service --no-pager -l || true
exit 1

