#!/bin/bash
# ==============================================================================
# NOTA DE SEGURANÇA E ARQUITETURA REAL (CONVENÇÃO ATUAL):
# 10.99.0.1 -> AMBIENTE DE PRODUÇÃO (Runtime Puro, Traefik, Monitoramento SOC)
# 10.99.0.3 -> BANCO DE DADOS DE PRODUÇÃO DEDICADO (PostgreSQL Bare-metal Appliance)
# 10.99.0.4 -> AMBIENTE DE DESENVOLVIMENTO, HOMOLOGAÇÃO & BUILDER DEPLOYS (GitOps)
# ==============================================================================
# ⚠️  CAUTION: ESTE SCRIPT REPLICA AS CONFIGURAÇÕES DE SEGURANÇA DA VPS 1.
# CERTIFIQUE-SE DE QUE A "PRIVATEKEY" DO WIREGUARD DA VPS 10.99.0.3 ESTEJA DISPONÍVEL.
# AS CHAVES SSH E AS CONFIGURAÇÕES DO WIREGUARD SÓ SERÃO CRIADAS SE NÃO EXISTIREM.
# ==============================================================================
# V8 BUNKER EXTREMO FINAL SUPREMA (VERSÃO BANCO DE DADOS DE PRODUÇÃO DEDICADO 10.99.0.3)
# AGENTE DE MONITORAMENTO (MÉTRICAS E LOGS ENVIADOS PARA A VPS 1)
# =========================================================
set -eo pipefail

echo "🚀 INICIANDO V8 BUNKER EXTREMO FINAL SUPREMA NA VPS 3 (BANCO DE DADOS DEDICADO)..."

# =========================
# 1. VARIÁVEIS DA INFRA
# =========================
USER_NAME="deploy"
PUBKEY="ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIMzqvHpWO69vdujhyeFaKmOssT5leqIUQsknJiFzHKlK rui@DESKTOP-K5Q17QK"
SERVER_VPN_IP="10.99.0.3"          # IP desta VPS na WireGuard
SERVER_GATEWAY_IP="10.99.0.1"      # IP da VPS 1 (Hub do Monitoramento)
VPN_SUBNET="10.99.0.0/24"
WG_SERVER_PUBKEY="jUWnuc+82vQ6kLMSI7W1i7hBRBgQKcaSZ8yJy56QSUw="
WG_SERVER_ENDPOINT="158.220.109.237:51820" # IP Público da VPS 1
DOMAIN_APP="dev.clube67.com"       # Domínio de Desenvolvimento
EMAIL="ruibto@gmail.com"
VPS2_DEV_PUBKEY="ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKm085+8paXXj9AzUa00dhuB1IH2/Y4uTStU1zm2I7QZ deploy@vmi2797860"
VPS1_PUBKEY="ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOm8XdsuqpRMM+1y4w4onc+VhPTtqR4iEFJYnA7SRNXS deploy@vmi2849674"

# =========================
# 2. BASE & PACOTES
# =========================
echo "🚀 Atualizando sistema e instalando pacotes base..."
apt update && apt upgrade -y
apt install -y curl ufw fail2ban auditd apparmor apparmor-utils \
               ca-certificates gnupg lsb-release htop jq acl wireguard

systemctl enable auditd || true
systemctl enable fail2ban || true

# =========================
# 3. USUÁRIO + SSH HARDEN + SUDO (NOPASSWD)
# =========================
echo "🚀 Criando usuário deploy e blindando SSH..."
id -u $USER_NAME &>/dev/null || adduser --disabled-password --gecos "" $USER_NAME
usermod -aG sudo,adm $USER_NAME

echo "$USER_NAME ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/$USER_NAME
chmod 0440 /etc/sudoers.d/$USER_NAME

mkdir -p /home/$USER_NAME/.ssh
echo "$PUBKEY" > /home/$USER_NAME/.ssh/authorized_keys
[[ -n "$VPS2_DEV_PUBKEY" ]] && grep -q "$VPS2_DEV_PUBKEY" /home/$USER_NAME/.ssh/authorized_keys || echo "$VPS2_DEV_PUBKEY" >> /home/$USER_NAME/.ssh/authorized_keys
[[ -n "$VPS1_PUBKEY" ]] && grep -q "$VPS1_PUBKEY" /home/$USER_NAME/.ssh/authorized_keys || echo "$VPS1_PUBKEY" >> /home/$USER_NAME/.ssh/authorized_keys
chmod 700 /home/$USER_NAME/.ssh
chmod 600 /home/$USER_NAME/.ssh/authorized_keys

# 👉 Proteção: Só cria a chave se ela não existir
if [[ ! -f /home/$USER_NAME/.ssh/id_ed25519 ]]; then
    echo "🚀 Replicando chave SSH privada..."
    cat <<EOF > /home/$USER_NAME/.ssh/id_ed25519
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
QyNTUxOQAAACA7022Ve09QNg3CELPHbj6psUsufcuLBwJqm7i8mWgWXAAAAJglHptaJR6b
WgAAAAtzc2gtZWQyNTUxOQAAACA7022Ve09QNg3CELPHbj6psUsufcuLBwJqm7i8mWgWXA
AAAEASb797x5GRsuKmM3DpBPiY8iPiyyPdrlnn9FmLTmn7BTvTbZV7T1A2DcIQs8duPqmx
Sy59y4sHAmqbuLyZaBZcAAAAEWRlcGxveUB2bWkyODQ5Njc0AQIDBA==
-----END OPENSSH PRIVATE KEY-----
EOF
    chmod 600 /home/$USER_NAME/.ssh/id_ed25519
    chown -R $USER_NAME:$USER_NAME /home/$USER_NAME/.ssh
else
    echo "⚠️  Chave SSH id_ed25519 já existe. Pulando criação."
fi

su - $USER_NAME -c "[[ -f ~/.ssh/id_ed25519.pub ]] || ssh-keygen -y -f ~/.ssh/id_ed25519 > ~/.ssh/id_ed25519.pub"

sed -i 's/^#\?PasswordAuthentication .*/PasswordAuthentication no/' /etc/ssh/sshd_config
sed -i 's/^#\?PermitRootLogin .*/PermitRootLogin no/' /etc/ssh/sshd_config
grep -q "^AllowUsers" /etc/ssh/sshd_config || echo "AllowUsers $USER_NAME" >> /etc/ssh/sshd_config

# =========================
# 4. FIREWALL (UFW)
# =========================
echo "🚀 Configurando regras do Firewall (UFW)..."
ufw default deny incoming
ufw default allow outgoing
ufw allow 80/tcp
ufw allow 443/tcp
ufw allow 52830/udp # Porta local do WG neste Peer
ufw allow from $VPN_SUBNET

# =========================
# 5. CONFIGURAÇÃO WIREGUARD (PEER)
# =========================
if [[ ! -f /etc/wireguard/wg0.conf ]]; then
    echo "🚀 Criando configuração do WireGuard (Peer)..."
    mkdir -p /etc/wireguard
    cat <<EOF > /etc/wireguard/wg0.conf
[Interface]
Address = $SERVER_VPN_IP/24
PrivateKey = 8Ck983MKEOVnskrvglzSOxWzR1ybZjQldl5VY2vctWc=
ListenPort = 52830

[Peer]
PublicKey = $WG_SERVER_PUBKEY
AllowedIPs = $VPN_SUBNET
Endpoint = $WG_SERVER_ENDPOINT
PersistentKeepalive = 25
EOF
    chmod 600 /etc/wireguard/wg0.conf
else
    echo "⚠️  Configuração do WireGuard (/etc/wireguard/wg0.conf) já existe. Pulando criação."
fi
systemctl enable wg-quick@wg0 || true

# =========================
# 6. SYSCTL HARDENING & NOEXEC
# =========================
echo "🚀 Aplicando Hardening no Kernel..."
grep -q "net.ipv4.ip_unprivileged_port_start" /etc/sysctl.conf || cat >> /etc/sysctl.conf <<EOF
kernel.kptr_restrict=2
kernel.yama.ptrace_scope=2
net.ipv4.ip_forward=1
net.ipv4.conf.all.accept_redirects=0
net.ipv4.conf.all.send_redirects=0
net.ipv4.conf.all.accept_source_route=0
net.ipv4.ip_unprivileged_port_start=80
EOF

# =========================
# 7. AGENTE DE MONITORAMENTO (SOC AGENT)
# =========================
echo "🚀 Preparando arquivos do Agente de Monitoramento..."
SOC_DIR="/opt/soc"
mkdir -p $SOC_DIR/promtail

cat > $SOC_DIR/promtail/config.yml <<EOF
server:
  http_listen_port: 9080
positions:
  filename: /tmp/positions.yaml
clients:
  - url: http://$SERVER_GATEWAY_IP:3100/loki/api/v1/push
scrape_configs:
  - job_name: falco_vps3
    static_configs:
      - targets: [localhost]
        labels:
          vps: vps3_desenvolvimento
          job: falco
          __path__: /var/log/falco.log
  - job_name: varlogs_vps3
    static_configs:
      - targets: [localhost]
        labels:
          vps: vps3_desenvolvimento
          job: varlogs
          __path__: /var/log/*.log
EOF

# =========================
# 8. CROWDSEC & FALCO (EDR)
# =========================
echo "🚀 Configurando EDR: CrowdSec + Falco..."
curl -s https://packagecloud.io/install/repositories/crowdsec/crowdsec/script.deb.sh | bash
apt install -y crowdsec crowdsec-firewall-bouncer-nftables

curl -s https://falco.org/repo/falcosecurity-packages.asc | apt-key add -
echo "deb https://download.falco.org/packages/deb stable main" > /etc/apt/sources.list.d/falco.list
apt update && apt install -y falco

mkdir -p /var/log
touch /var/log/falco.log
chmod 644 /var/log/falco.log
setfacl -R -m u:$USER_NAME:rx /var/log || true

# Script para enviar alertas para o Hub Central via CrowdSec local (opcional) ou logs
cat > /usr/local/bin/falco-active-response.sh <<'EOF'
#!/bin/bash
LOG="/var/log/falco-response.log"
while read -r INPUT; do
  echo "[$(date)] EVENTO LIDO: $INPUT" >> $LOG
  PID=$(echo "$INPUT" | grep -oP 'pid=\K[0-9]+' | head -n1)
  if [[ -n "$PID" ]]; then
    kill -9 "$PID" 2>/dev/null
    echo "[$(date)] PROCESSO MORTO PELO FALCO: $PID" >> $LOG
  fi
done
EOF
chmod +x /usr/local/bin/falco-active-response.sh

sed -i 's/^#file_output:/file_output:/g' /etc/falco/falco.yaml || true
grep -q "falco-active-response" /etc/falco/falco.yaml || cat >> /etc/falco/falco.yaml <<EOF
file_output:
  enabled: true
  filename: /var/log/falco.log
program_output:
  enabled: true
  keep_alive: true
  program: "/usr/local/bin/falco-active-response.sh"
EOF

# =========================
# 10. DOCKER ROOTLESS & STACKS DEV
# =========================
echo "🚀 Instalando Docker Rootless..."
apt install -y uidmap dbus-user-session docker-compose-plugin
su - $USER_NAME -c "[[ -f ~/bin/dockerd ]] || curl -fsSL https://get.docker.com/rootless | sh"
loginctl enable-linger $USER_NAME

DEPLOY_UID=$(id -u $USER_NAME)
mkdir -p /home/$USER_NAME/stack/{traefik/letsencrypt,soc,portainer/data}
touch /home/$USER_NAME/stack/traefik/letsencrypt/acme.json
chmod 600 /home/$USER_NAME/stack/traefik/letsencrypt/acme.json

# Stack do Monitoramento Simplificada (Apenas Agentes)
cat > /home/$USER_NAME/stack/soc/docker-compose.yml <<EOF
services:
  promtail:
    image: grafana/promtail:2.9.0
    restart: always
    volumes:
      - /var/log:/var/log:ro
      - /opt/soc/promtail:/etc/promtail:ro
    command: -config.file=/etc/promtail/config.yml
    networks:
      - soc
  node-exporter:
    image: prom/node-exporter:latest
    restart: always
    volumes:
      - /proc:/host/proc:ro
      - /sys:/host/sys:ro
      - /:/rootfs:ro
    command:
      - '--path.procfs=/host/proc'
      - '--path.rootfs=/rootfs'
      - '--path.sysfs=/host/sys'
      - '--collector.filesystem.mount-points-exclude=^/(sys|proc|dev|host|etc)($$|/)'
    networks:
      - soc
networks:
  soc:
    external: true
EOF

chown -R $USER_NAME:$USER_NAME /home/$USER_NAME/stack

# =========================
# 12. TELA FINAL
# =========================
clear
echo "*******************************************************************************"
echo "* 🚀 INSTALAÇÃO VPS 3 (DESENVOLVIMENTO) CONCLUÍDA!                            *"
echo "*******************************************************************************"
echo "⚙️  AMBIENTE: DESENVOLVIMENTO INTEGRADO AO SOC (VPS 1)"
echo "-------------------------------------------------------------------------------"
echo "👉 Usuário: $USER_NAME"
echo "👉 SSH: ssh $USER_NAME@$SERVER_VPN_IP"
echo ""
echo "📊 MONITORAMENTO CENTRALIZADO"
echo "-------------------------------------------------------------------------------"
echo "👉 Acesse os painéis na VPS 1 ($SERVER_GATEWAY_IP:3000)"
echo "*******************************************************************************"
read -p "Pressione [ENTER] para reiniciar e selar o Bunker..."
reboot
