#!/bin/bash
set -e

echo "[1] Finding what holds port 80..."
ss -tlnp | grep :80 || echo "nothing"
lsof -i :80 2>/dev/null || echo "lsof: nothing"

echo "[2] AGGRESSIVE kill port 80..."
systemctl stop nginx 2>/dev/null || true
systemctl disable nginx 2>/dev/null || true
# Kill all python3 http servers
pkill -9 -f 'http.server' 2>/dev/null || true
# Kill anything on port 80
fuser -k -9 80/tcp 2>/dev/null || true
sleep 3

echo "[3] Port 80 check after kill..."
ss -tlnp | grep :80 && echo "STILL_OCCUPIED" || echo "PORT_80_FREE"

echo "[4] Getting SSL cert..."
certbot certonly --standalone -d 92-118-168-101.nip.io \
  --non-interactive --agree-tos --email security@test.com \
  --preferred-challenges http 2>&1 | tail -10

echo "[5] Cert check..."
ls -la /etc/letsencrypt/live/92-118-168-101.nip.io/ 2>&1 || echo "NO_CERT"

echo "[6] Starting HTTPS server on 443..."
cat > /root/https_server.py << 'PYEOF'
import http.server, ssl, os
os.chdir("/root")
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(
    "/etc/letsencrypt/live/92-118-168-101.nip.io/fullchain.pem",
    "/etc/letsencrypt/live/92-118-168-101.nip.io/privkey.pem"
)
server = http.server.HTTPServer(("0.0.0.0", 443), http.server.SimpleHTTPRequestHandler)
server.socket = context.wrap_socket(server.socket, server_side=True)
print("HTTPS OK on 443")
server.serve_forever()
PYEOF

nohup python3 /root/https_server.py > /tmp/https.log 2>&1 &
sleep 3

echo "[7] HTTPS test..."
curl -sk -o /dev/null -w '%{http_code}' https://92-118-168-101.nip.io/miniapp.html
echo ""
echo "[8] Content test..."
curl -sk https://92-118-168-101.nip.io/miniapp.html 2>/dev/null | head -3
echo "SCRIPT_DONE"
