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

# STEP 1: NUKE everything on port 80
systemctl stop tg-relay.service nginx zc-http.service zc-bot.service 2>/dev/null || true
systemctl disable tg-relay.service nginx 2>/dev/null || true
pkill -9 -f 'http.server' || true
pkill -9 -f 'https_server' || true
pkill -9 -f 'bot.py' || true
pkill -9 -f 'c2_file_server' || true
for i in 1 2 3; do fuser -k -9 80/tcp 2>/dev/null || true; sleep 1; done
sleep 2

echo "=== PORT CHECK ==="
ss -tlnp | grep :80 && echo "PORT80_BUSY" || echo "PORT80_FREE"

# STEP 2: certbot
certbot certonly --standalone -d 92-118-168-101.nip.io \
  --non-interactive --agree-tos --email security@test.com \
  --preferred-challenges http 2>&1
CERT_STATUS=$?
echo "CERT_STATUS=$CERT_STATUS"

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

# STEP 3: Start HTTPS server if cert exists
if [ -f /etc/letsencrypt/live/92-118-168-101.nip.io/fullchain.pem ]; then
    echo "=== CERT EXISTS, STARTING HTTPS ==="
    nohup python3 /root/https_server.py > /tmp/https_run.log 2>&1 &
    sleep 3
    curl -sk -o /dev/null -w 'HTTPS_STATUS=%{http_code}\n' https://92-118-168-101.nip.io/miniapp.html
    echo "=== DONE ==="
else
    echo "=== NO CERT ==="
fi
