#!/usr/bin/env bash
# Publica o painel em um domínio com HTTPS (Let's Encrypt), usando o Apache OU o Nginx
# que já estiver rodando neste servidor (se nenhum estiver, instala o Nginx).
#
# Uso:  sudo ./configurar-https.sh srv.realshopcar.com.br seu-email@dominio.com.br
#
# Antes:
#   1) crie no DNS um registro A  srv.realshopcar.com.br -> IP público deste servidor
#   2) libere as portas 80 e 443 (firewall / roteador, se houver NAT)
set -euo pipefail

[ "$(id -u)" -eq 0 ] || { echo "Execute como root: sudo $0 DOMINIO EMAIL"; exit 1; }
DOMAIN="${1:-}"; EMAIL="${2:-}"
[ -n "$DOMAIN" ] && [ -n "$EMAIL" ] || { sed -n '2,9p' "$0"; exit 1; }
[[ "$DOMAIN" =~ ^[A-Za-z0-9]([A-Za-z0-9.-]*[A-Za-z0-9])?$ ]] || { echo "Domínio inválido."; exit 1; }
PORT="$(systemctl show painel-reinicios -p Environment 2>/dev/null | grep -o 'PORT=[0-9]*' | cut -d= -f2 || true)"
PORT="${PORT:-8080}"

systemctl is-active --quiet painel-reinicios || { echo "O serviço painel-reinicios não está rodando. Rode antes o instalar-painel.sh."; exit 1; }

echo "==> Conferindo DNS de $DOMAIN"
DNSIP="$(getent ahostsv4 "$DOMAIN" 2>/dev/null | awk 'NR==1{print $1}' || true)"
PUBIP="$(curl -4 -fsS --max-time 6 https://api.ipify.org 2>/dev/null || true)"
echo "    DNS aponta para: ${DNSIP:-(não resolve)}   |   IP público deste servidor: ${PUBIP:-(não consegui descobrir)}"
if [ -z "$DNSIP" ]; then
  echo "ERRO: o domínio ainda não resolve. Crie o registro A no DNS e aguarde propagar."; exit 1
fi
if [ -n "$PUBIP" ] && [ "$DNSIP" != "$PUBIP" ] && [ "${FORCE:-0}" != "1" ]; then
  echo "AVISO: o DNS não aponta para este servidor (pode ser Cloudflare/proxy ou NAT)."
  read -r -p "Continuar mesmo assim? [s/N] " r; [[ "$r" =~ ^[sSyY]$ ]] || exit 1
fi

# --- qual servidor web usar? ---
if systemctl is-active --quiet apache2; then WEB=apache
elif systemctl is-active --quiet nginx; then WEB=nginx
else WEB=nginx; fi
echo "==> Servidor web: $WEB"

apt_update() { apt-get update -y --allow-releaseinfo-change || echo "    aviso: apt update com erro (repositório de terceiros?), seguindo"; }

if [ "$WEB" = apache ]; then
  apt_update; apt-get install -y certbot python3-certbot-apache
  a2enmod proxy proxy_http headers ssl rewrite >/dev/null
  cat > /etc/apache2/sites-available/painel-reinicios.conf <<EOF
<VirtualHost *:80>
    ServerName $DOMAIN
    ProxyPreserveHost On
    # impede que o cliente forje o IP de origem
    RequestHeader unset X-Forwarded-For
    ProxyPass / http://127.0.0.1:$PORT/ timeout=120
    ProxyPassReverse / http://127.0.0.1:$PORT/
</VirtualHost>
EOF
  a2ensite painel-reinicios >/dev/null
  apache2ctl configtest
  systemctl reload apache2
  echo "==> Emitindo certificado HTTPS"
  certbot --apache -d "$DOMAIN" -m "$EMAIL" --agree-tos --no-eff-email -n --redirect
  apache2ctl configtest && systemctl reload apache2
else
  apt_update; apt-get install -y nginx certbot python3-certbot-nginx
  cat > /etc/nginx/sites-available/painel-reinicios <<'EOF'
server {
    listen 80;
    server_name __DOMAIN__;
    location / {
        proxy_pass http://127.0.0.1:__PORT__;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_read_timeout 120s;
    }
}
EOF
  sed -i "s/__DOMAIN__/$DOMAIN/; s/__PORT__/$PORT/" /etc/nginx/sites-available/painel-reinicios
  ln -sf /etc/nginx/sites-available/painel-reinicios /etc/nginx/sites-enabled/painel-reinicios
  nginx -t
  systemctl enable --now nginx >/dev/null 2>&1 || true
  systemctl reload nginx
  echo "==> Emitindo certificado HTTPS"
  certbot --nginx -d "$DOMAIN" -m "$EMAIL" --agree-tos --no-eff-email -n --redirect
fi

echo "==> Ajustando o painel para rodar atrás do proxy (somente local + cookie seguro)"
mkdir -p /etc/systemd/system/painel-reinicios.service.d
cat > /etc/systemd/system/painel-reinicios.service.d/https.conf <<EOF
[Service]
Environment=HOST=127.0.0.1
Environment=COOKIE_SECURE=1
Environment=TRUST_PROXY=1
EOF
systemctl daemon-reload
systemctl restart painel-reinicios

if command -v ufw >/dev/null 2>&1 && ufw status | grep -q "Status: active"; then
  echo "==> Firewall (ufw): liberando 80 e 443"
  ufw allow 80/tcp >/dev/null; ufw allow 443/tcp >/dev/null
fi

echo
echo "=============================================================="
echo " Pronto:  https://$DOMAIN"
echo " A porta $PORT do painel agora responde só localmente (127.0.0.1)."
echo " Renovação do certificado é automática (certbot.timer)."
echo "=============================================================="
