#!/bin/bash
exec > /tmp/setup2_log.txt 2>&1
set -x

# Check if port 80 is REALLY free
echo "=== EXACT PORT 80 CHECK ==="
ss -tlnp | grep -w ':80' || echo "PORT_80_TRULY_FREE"
ss -anp | grep ':80 ' | head -5

# Test binding port 80 with Python
python3 -c "
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    s.bind(('0.0.0.0', 80))
    s.listen(1)
    print('BIND_80_SUCCESS')
    s.close()
except Exception as e:
    print(f'BIND_80_FAILED: {e}')
" 2>&1

# If direct binding works, try certbot again
# But first, use alternative: http-01-port + iptables redirect
echo "=== TRYING IPTABLES REDIRECT METHOD ==="
iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 9080 2>&1
certbot certonly --standalone --http-01-port 9080 -d 92-118-168-101.nip.io \
  --non-interactive --agree-tos --email security@test.com 2>&1
CERT_STATUS=$?
iptables -t nat -D PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 9080 2>&1
echo "CERT_STATUS=$CERT_STATUS"

# Check cert
ls -la /etc/letsencrypt/live/92-118-168-101.nip.io/ 2>&1

if [ -f /etc/letsencrypt/live/92-118-168-101.nip.io/fullchain.pem ]; then
    echo "=== CERT OK! Starting HTTPS server ==="
    pkill -9 -f https_server 2>/dev/null || true
    sleep 1
    cd /root && nohup python3 /root/https_server.py > /tmp/https_run.log 2>&1 &
    sleep 4
    curl -sk -o /dev/null -w 'HTTPS=%{http_code}\n' https://92-118-168-101.nip.io/miniapp.html
    curl -sk https://92-118-168-101.nip.io/miniapp.html 2>/dev/null | head -3
    echo "=== SUCCESS ==="
else
    echo "=== CERT FAILED. Trying DNS check ==="
    # Maybe nip.io DNS doesn't resolve
    dig +short 92-118-168-101.nip.io 2>&1 || nslookup 92-118-168-101.nip.io 2>&1
    curl -s http://92-118-168-101.nip.io 2>&1 | head -3
    echo "=== END ==="
fi
