#!/usr/bin/env bash
# Prepara un servidor Debian 12 limpio para correr la plataforma con Docker.
# Uso (como root):  bash scripts/server-setup.sh
set -euo pipefail

echo "== Sistema y seguridad básica =="
apt-get update && apt-get -y upgrade
apt-get install -y ca-certificates curl gnupg ufw fail2ban unattended-upgrades
dpkg-reconfigure -f noninteractive unattended-upgrades
timedatectl set-timezone UTC

echo "== Firewall: solo SSH, HTTP y HTTPS =="
ufw allow OpenSSH && ufw allow 80/tcp && ufw allow 443/tcp && ufw --force enable

echo "== Swap de 2 GB (el build de Next necesita memoria) =="
if ! swapon --show | grep -q swapfile; then
  fallocate -l 2G /swapfile && chmod 600 /swapfile && mkswap /swapfile && swapon /swapfile
  echo '/swapfile none swap sw 0 0' >> /etc/fstab
fi

echo "== Docker Engine + Compose =="
install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/debian/gpg | gpg --dearmor -o /etc/apt/keyrings/docker.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/debian bookworm stable" > /etc/apt/sources.list.d/docker.list
apt-get update && apt-get install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin
systemctl enable --now docker

echo "== Backup diario de la base a las 04:00 UTC =="
APP_DIR=$(cd "$(dirname "$0")/.." && pwd)
( crontab -l 2>/dev/null | grep -v backup.sh; echo "0 4 * * * cd $APP_DIR && bash scripts/backup.sh >> backups/backup.log 2>&1" ) | crontab -

echo
echo "Listo. Siguiente paso:"
echo "  cd $APP_DIR && cp .env.example .env.production && nano .env.production"
echo "  docker compose --env-file .env.production up -d --build"
