#!/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)
# ==============================================================================
# V8 BUNKER EXTREMO FINAL SUPREMA (VERSÃO PRODUÇÃO 10.99.0.1)
# HUB DE MONITORAMENTO CENTRALIZADO (RECEBE LOGS E MÉTRICAS DE TODAS AS VPSs)
# =========================================================
set -eo pipefail

echo "🚀 INICIANDO V8 BUNKER EXTREMO FINAL SUPREMA NA VPS 1 (PRODUÇÃO)..."

# =========================
# 1. VARIÁVEIS DA INFRA
# =========================
USER_NAME="deploy"
PUBKEY="ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOnD6GW6oVuY1DcfCQSUQV/JNHa35A2Or1K3X1gEC8D/ rui@DESKTOP-K5Q17QK"
WG_PORT="52830"
VPN_SUBNET="10.99.0.0/24"
SERVER_VPN_IP="10.99.0.1"
DOMAIN_APP="clube67.com"
EMAIL="ruibto@gmail.com"
VPS2_DEV_PUBKEY="ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKm085+8paXXj9AzUa00dhuB1IH2/Y4uTStU1zm2I7QZ deploy@vmi2797860"

# =========================
# 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

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
chmod 700 /home/$USER_NAME/.ssh
chmod 600 /home/$USER_NAME/.ssh/authorized_keys
chown -R $USER_NAME:$USER_NAME /home/$USER_NAME/.ssh

su - $USER_NAME -c "[[ -f ~/.ssh/id_ed25519 ]] || ssh-keygen -t ed25519 -N '' -f ~/.ssh/id_ed25519"

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 $WG_PORT/udp
ufw allow from $VPN_SUBNET

# =========================
# 5. 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

grep -q "/tmp tmpfs" /etc/fstab || echo "tmpfs /tmp tmpfs defaults,noexec,nosuid 0 0" >> /etc/fstab
grep -q "/dev/shm tmpfs" /etc/fstab || echo "tmpfs /dev/shm tmpfs defaults,noexec,nosuid 0 0" >> /etc/fstab
grep -q "/var/tmp tmpfs" /etc/fstab || echo "tmpfs /var/tmp tmpfs defaults,noexec,nosuid 0 0" >> /etc/fstab

# =========================
# 6. QUARENTENA INTELIGENTE & EDR
# =========================
# (Mesma lógica do script anterior, mantida para proteção local da VPS 1)
cat > /usr/local/bin/quarantine-guard.sh <<'EOF'
#!/bin/bash
LOG="/var/log/quarantine.log"
FORENSIC="/var/log/quarantine_forensic.log"
THRESHOLD=80
MEM=$(free | awk '/Mem:/ {printf("%.0f", $3/$2 * 100)}')
if [ "$MEM" -lt "$THRESHOLD" ]; then exit 0; fi
echo "[$(date)] MEMORIA CRITICA: $MEM%" >> $LOG
ps -eo pid,%mem,user,cmd --sort=-%mem | head -n 15 | tail -n +2 | while read -r PID MEM_USAGE USER CMD
do
  NAME=$(echo "$CMD" | awk '{print $1}' | xargs basename)
  BIN_PATH=$(readlink -f /proc/$PID/exe 2>/dev/null || echo "")
  CWD=$(readlink -f /proc/$PID/cwd 2>/dev/null || echo "")
  if [[ "$CWD" == /tmp* ]] || [[ "$BIN_PATH" == /tmp* ]] || [[ "$NAME" =~ (xmrig|kinsing|kdevtmpfsi) ]]; then
    kill -9 $PID 2>/dev/null
    echo "[$(date)] PROCESSO ELIMINADO: $NAME ($PID)" >> $LOG
  fi
done
EOF
chmod +x /usr/local/bin/quarantine-guard.sh
grep -q "quarantine-guard" /etc/crontab || echo "*/1 * * * * root /usr/local/bin/quarantine-guard.sh" >> /etc/crontab

# =========================
# 7. CROWDSEC & FALCO (EDR)
# =========================
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

# =========================
# 8. CONFIGURAÇÃO MONITORAMENTO CENTRAL (HUB)
# =========================
echo "🚀 Preparando HUB de Monitoramento Central..."
SOC_DIR="/opt/soc"
mkdir -p $SOC_DIR/{grafana/provisioning/datasources,grafana/provisioning/dashboards,grafana/provisioning/alerting,grafana/dashboards,prometheus,promtail}

# Prometheus configurado para monitorar Produção (10.99.0.1), Desenvolvimento (10.99.0.3) e WhatsApp (10.99.0.4)
cat > $SOC_DIR/prometheus/prometheus.yml <<EOF
global:
  scrape_interval: 15s
scrape_configs:
  - job_name: "producao"
    static_configs:
      - targets: ["node-exporter:9100"]
  - job_name: "desenvolvimento"
    static_configs:
      - targets: ["10.99.0.3:9100"]
  - job_name: "whatsapp"
    static_configs:
      - targets: ["10.99.0.4:9100"]
EOF

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

cat > $SOC_DIR/grafana/provisioning/datasources/datasources.yml <<EOF
apiVersion: 1
datasources:
  - name: Prometheus
    type: prometheus
    url: http://prometheus:9090
  - name: Loki
    type: loki
    url: http://loki:3100
EOF

# Dashboard unificado (Exemplo simplificado)
cat > $SOC_DIR/grafana/dashboards/soc.json <<'EOF'
{
  "title": "SOC GLOBAL OVERVIEW",
  "panels": [
    {
      "type": "stat",
      "title": "CPU Produção",
      "targets": [ { "expr": "100 - (avg(rate(node_cpu_seconds_total{job=\"producao\",mode=\"idle\"}[5m])) * 100)" } ]
    },
    {
      "type": "stat",
      "title": "CPU Desenvolvimento",
      "gridPos": { "x": 12, "y": 0, "h": 5, "w": 12 },
      "targets": [ { "expr": "100 - (avg(rate(node_cpu_seconds_total{job=\"desenvolvimento\",mode=\"idle\"}[5m])) * 100)" } ]
    }
  ],
  "schemaVersion": 36,
  "version": 1
}
EOF

chown -R $USER_NAME:$USER_NAME $SOC_DIR

# =========================
# 9. APPARMOR FIX & 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)

# =========================
# 10. STACKS DE PRODUÇÃO
# =========================
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

cat > /home/$USER_NAME/stack/soc/docker-compose.yml <<EOF
services:
  grafana:
    image: grafana/grafana:latest
    restart: always
    ports:
      - "10.99.0.1:3000:3000"
    volumes:
      - "/home/$USER_NAME/stack/soc/grafana-data:/var/lib/grafana"
      - "/opt/soc/grafana/provisioning:/etc/grafana/provisioning"
      - "/opt/soc/grafana/dashboards:/var/lib/grafana/dashboards"
    networks:
      - soc
  loki:
    image: grafana/loki:2.9.0
    restart: always
    ports:
      - "10.99.0.1:3100:3100" # Aberto para receber logs das outras VPSs
    volumes:
      - "/home/$USER_NAME/stack/soc/loki-data:/loki"
    networks:
      - soc
  prometheus:
    image: prom/prometheus
    restart: always
    volumes:
      - "/opt/soc/prometheus:/etc/prometheus"
      - "/home/$USER_NAME/stack/soc/prom-data:/prometheus"
    networks:
      - soc
  node-exporter:
    image: prom/node-exporter:latest
    restart: always
    networks:
      - soc
networks:
  soc:
    external: true
EOF

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

# =========================
# 12. SELAGEM DO BUNKER E REBOOT
# =========================
echo "🚀 Finalizando Produção..."
ufw --force enable
su - $USER_NAME <<'EOSU'
export XDG_RUNTIME_DIR="/run/user/$(id -u)"
export DOCKER_HOST="unix://$XDG_RUNTIME_DIR/docker.sock"
systemctl --user enable --now docker || true
docker network create web || true
docker network create soc || true
cd $HOME/stack/soc && docker compose up -d
EOSU

echo "*******************************************************************************"
echo "* 🚀 HUB DE MONITORAMENTO CENTRALIZADO (PRODUÇÃO) PRONTO!                     *"
echo "*******************************************************************************"
echo "👉 Grafana: http://10.99.0.1:3000"
echo "👉 Esta VPS agora recebe métricas de 10.99.0.3 e 10.99.0.4"
echo "*******************************************************************************"
read -p "Pressione [ENTER] para reiniciar..."
reboot