#!/usr/bin/env bash
# =============================================================================
# RecreaHUB API — Nginx Setup CentOS 7
#
# Instala e configura Nginx no CentOS 7 via repositório EPEL.
# Suporte opcional a SSL/HTTPS com Let's Encrypt (certbot via EPEL).
#
# Uso:
#   sudo bash setup-nginx-centos7.sh
#   sudo bash setup-nginx-centos7.sh --ssl api.recreahub.com.br
#
# Pré-requisito:
#   A aplicação deve estar rodando na porta 3000 (via setup-centos7.sh).
# =============================================================================
set -euo pipefail

DEPLOY_DIR="/opt/recreahub-api"
NGINX_CONF_SRC="${DEPLOY_DIR}/scripts/setup-nginx-centos7.conf"
NGINX_CONF_DST="/etc/nginx/conf.d/recreahub-api.conf"
APP_PORT=3000
DOMAIN=""
ENABLE_SSL=false

# ── Cores para output ─────────────────────────────────────────────────────────
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

# ── Parse de argumentos ───────────────────────────────────────────────────────
while [[ $# -gt 0 ]]; do
  case "$1" in
    --ssl)
      ENABLE_SSL=true
      DOMAIN="${2:-}"
      if [ -z "${DOMAIN}" ]; then
        echo -e "${RED}ERRO: --ssl requer um domínio. Ex: --ssl api.recreahub.com.br${NC}"
        exit 1
      fi
      shift 2
      ;;
    *)
      echo -e "${RED}ERRO: Argumento desconhecido: $1${NC}"
      echo "Uso: sudo bash setup-nginx-centos7.sh [--ssl dominio.com]"
      exit 1
      ;;
  esac
done

echo ""
echo "============================================================"
echo "  RecreaHUB API — Nginx Setup CentOS 7"
if [ "${ENABLE_SSL}" = true ]; then
  echo "  Modo: HTTP + SSL (domínio: ${DOMAIN})"
else
  echo "  Modo: HTTP only"
fi
echo "============================================================"
echo ""

# ── 0. Verificar root ─────────────────────────────────────────────────────────
echo "[0/7] Verificando permissões..."
if [ "$EUID" -ne 0 ]; then
  echo -e "${RED}ERRO: Execute como root: sudo bash setup-nginx-centos7.sh${NC}"
  exit 1
fi
echo -e "  ${GREEN}OK${NC}: Executando como root"

# ── 1. Verificar CentOS 7 ─────────────────────────────────────────────────────
echo "[1/7] Verificando sistema operacional..."
if ! grep -q "CentOS Linux release 7" /etc/centos-release 2>/dev/null; then
  echo -e "${RED}ERRO: Este script é específico para CentOS 7.${NC}"
  exit 1
fi
echo -e "  ${GREEN}OK${NC}: CentOS 7 detectado"

# ── 2. Instalar EPEL e Nginx ──────────────────────────────────────────────────
echo "[2/7] Instalando EPEL release e Nginx..."

# Instalar EPEL se não disponível
if ! rpm -qa | grep -q "^epel-release"; then
  echo "  Instalando repositório EPEL..."
  yum install -y epel-release
  echo -e "  ${GREEN}OK${NC}: EPEL instalado"
else
  echo -e "  ${GREEN}OK${NC}: EPEL já está instalado"
fi

# Instalar Nginx
if command -v nginx &>/dev/null; then
  echo -e "  ${GREEN}OK${NC}: Nginx já instalado ($(nginx -v 2>&1)) — pulando"
else
  yum install -y nginx
  echo -e "  ${GREEN}OK${NC}: Nginx instalado"
fi

# ── 3. Copiar configuração do Nginx ───────────────────────────────────────────
echo "[3/7] Copiando configuração do Nginx..."

# Verificar se o arquivo de origem existe
if [ -f "${NGINX_CONF_SRC}" ]; then
  cp "${NGINX_CONF_SRC}" "${NGINX_CONF_DST}"
  echo -e "  ${GREEN}OK${NC}: Configuração copiada para ${NGINX_CONF_DST}"
elif [ -f "$(dirname "$0")/setup-nginx-centos7.conf" ]; then
  # Tentar encontrar no mesmo diretório do script
  cp "$(dirname "$0")/setup-nginx-centos7.conf" "${NGINX_CONF_DST}"
  echo -e "  ${GREEN}OK${NC}: Configuração copiada de $(dirname "$0")/setup-nginx-centos7.conf"
else
  echo -e "  ${YELLOW}AVISO${NC}: Arquivo de configuração não encontrado em ${NGINX_CONF_SRC}"
  echo "  Gerando configuração padrão em ${NGINX_CONF_DST}..."

  # Criar configuração padrão inline
  SERVER_NAME="${DOMAIN:-api.recreahub.com.br}"
  cat > "${NGINX_CONF_DST}" <<EOF
# RecreaHUB API — Nginx CentOS 7 (gerado automaticamente)
upstream recreahub_api {
    server 127.0.0.1:${APP_PORT};
    keepalive 64;
}

server {
    listen       80;
    server_name  ${SERVER_NAME};

    client_max_body_size 10m;

    gzip on;
    gzip_types application/json text/plain text/css application/javascript;
    gzip_min_length 1024;

    location /health {
        proxy_pass http://recreahub_api;
        access_log off;
    }

    location / {
        proxy_pass         http://recreahub_api;
        proxy_http_version 1.1;
        proxy_set_header   Upgrade    \$http_upgrade;
        proxy_set_header   Connection 'upgrade';
        proxy_set_header   Host       \$host;
        proxy_set_header   X-Real-IP  \$remote_addr;
        proxy_set_header   X-Forwarded-For   \$proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto \$scheme;
        proxy_cache_bypass \$http_upgrade;
        proxy_read_timeout 120s;
        proxy_connect_timeout 10s;
    }
}
EOF
  echo -e "  ${GREEN}OK${NC}: Configuração padrão gerada"
fi

# ── 4. Configurar SELinux para Nginx ──────────────────────────────────────────
echo "[4/7] Configurando SELinux para proxy Nginx → Node.js..."
if command -v getenforce &>/dev/null; then
  SELINUX_STATUS=$(getenforce)
  if [ "${SELINUX_STATUS}" != "Disabled" ]; then
    setsebool -P httpd_can_network_connect 1
    echo -e "  ${GREEN}OK${NC}: SELinux httpd_can_network_connect=1"
    echo "  (Necessário para Nginx fazer proxy para Node.js na porta ${APP_PORT})"
  else
    echo -e "  ${YELLOW}INFO${NC}: SELinux desabilitado — nenhuma configuração necessária"
  fi
else
  echo -e "  ${YELLOW}INFO${NC}: SELinux não disponível"
fi

# ── 5. Testar e iniciar Nginx ─────────────────────────────────────────────────
echo "[5/7] Testando configuração do Nginx..."
nginx -t
echo -e "  ${GREEN}OK${NC}: Configuração do Nginx válida"

echo "  Habilitando e iniciando Nginx..."
systemctl enable nginx
systemctl start nginx || systemctl restart nginx
echo -e "  ${GREEN}OK${NC}: Nginx habilitado e iniciado"

# ── 6. Configurar firewalld ───────────────────────────────────────────────────
echo "[6/7] Configurando firewalld..."
if systemctl is-active --quiet firewalld; then
  firewall-cmd --permanent --add-service=http
  firewall-cmd --permanent --add-service=https
  firewall-cmd --reload
  echo -e "  ${GREEN}OK${NC}: Portas 80 e 443 abertas no firewalld"
else
  echo -e "  ${YELLOW}AVISO${NC}: firewalld não está ativo. Iniciando..."
  systemctl start firewalld
  systemctl enable firewalld
  firewall-cmd --permanent --add-service=http
  firewall-cmd --permanent --add-service=https
  firewall-cmd --reload
  echo -e "  ${GREEN}OK${NC}: firewalld iniciado e portas abertas"
fi

# ── 7. Configurar SSL com Let's Encrypt (opcional) ───────────────────────────
echo "[7/7] Configuração SSL..."
if [ "${ENABLE_SSL}" = true ]; then
  echo "  Instalando certbot (EPEL)..."

  # Instalar certbot e plugin Nginx via EPEL
  if ! command -v certbot &>/dev/null; then
    yum install -y certbot python2-certbot-nginx
    echo -e "  ${GREEN}OK${NC}: certbot e python2-certbot-nginx instalados"
  else
    echo -e "  ${GREEN}OK${NC}: certbot já instalado"
  fi

  echo "  Obtendo certificado SSL para ${DOMAIN}..."
  echo -e "  ${YELLOW}NOTA${NC}: Certifique-se de que o DNS de ${DOMAIN} aponta para este servidor."
  echo ""

  certbot --nginx -d "${DOMAIN}" --non-interactive --agree-tos \
    --email "admin@recreahub.com.br" --redirect \
    || {
      echo -e "  ${YELLOW}AVISO${NC}: certbot falhou. Tente manualmente:"
      echo "  certbot --nginx -d ${DOMAIN}"
    }

  # Configurar renovação automática via cron
  if ! crontab -l 2>/dev/null | grep -q "certbot renew"; then
    (crontab -l 2>/dev/null; echo "0 2 * * * /usr/bin/certbot renew --quiet --post-hook 'systemctl reload nginx'") | crontab -
    echo -e "  ${GREEN}OK${NC}: Renovação automática de certificado configurada (cron: 2h diariamente)"
  fi
else
  echo -e "  ${YELLOW}INFO${NC}: SSL não solicitado. Para habilitar mais tarde:"
  echo "  sudo bash setup-nginx-centos7.sh --ssl api.recreahub.com.br"
fi

# ── Resumo final ──────────────────────────────────────────────────────────────
SERVER_IP=$(hostname -I | awk '{print $1}' 2>/dev/null || echo "api.recreahub.com.br")

echo ""
echo "============================================================"
echo -e "  ${GREEN}Nginx Setup CentOS 7 Concluído!${NC}"
echo "============================================================"
echo ""
echo "  HTTP  : http://${SERVER_IP}"
if [ "${ENABLE_SSL}" = true ]; then
  echo "  HTTPS : https://${DOMAIN}"
fi
echo "  Config: ${NGINX_CONF_DST}"
echo ""
echo "  Comandos úteis:"
echo "    nginx -t                    — testar configuração"
echo "    systemctl reload nginx      — recarregar sem downtime"
echo "    systemctl status nginx      — status do serviço"
echo "    journalctl -u nginx -f      — logs em tempo real"
echo ""
if [ "${ENABLE_SSL}" = true ]; then
  echo "  Renovação SSL:"
  echo "    certbot renew --dry-run     — testar renovação"
  echo "    certbot renew               — renovar certificados"
fi
echo "============================================================"
