#!/usr/bin/env bash
# ============================================================================
# server-setup.sh — Provisión y hardening inicial del VPS (Ubuntu 22.04/24.04)
# ----------------------------------------------------------------------------
# Ejecutar UNA VEZ como root (o con sudo) en un VPS recién creado:
#   sudo bash server-setup.sh
#
# Hace: paquetes base, Node 20, build tools (para compilar better-sqlite3),
# PM2, Nginx, Certbot, UFW (22/80/443), Fail2ban, usuario de despliegue y
# carpetas de la app. NO toca tu config SSH automáticamente: ver el aviso final.
# ============================================================================
set -euo pipefail

DEPLOY_USER="${DEPLOY_USER:-deploy}"
APP_DIR="/var/www/peninsula"

log() { printf '\n\033[1;34m==> %s\033[0m\n' "$*"; }

if [[ $EUID -ne 0 ]]; then echo "Ejecuta como root o con sudo."; exit 1; fi

log "Actualizando paquetes base"
export DEBIAN_FRONTEND=noninteractive
apt-get update -y
apt-get upgrade -y
apt-get install -y curl ca-certificates gnupg git ufw fail2ban nginx \
  build-essential python3 ufw rsync

log "Instalando Node.js 20 LTS (NodeSource)"
if ! command -v node >/dev/null 2>&1 || [[ "$(node -v | cut -dv -f2 | cut -d. -f1)" -lt 18 ]]; then
  curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
  apt-get install -y nodejs
fi
node -v && npm -v

log "Instalando PM2 (gestor de procesos) y Certbot"
npm install -g pm2
apt-get install -y certbot python3-certbot-nginx

log "Creando usuario de despliegue '$DEPLOY_USER'"
if ! id "$DEPLOY_USER" >/dev/null 2>&1; then
  adduser --disabled-password --gecos "" "$DEPLOY_USER"
  usermod -aG www-data "$DEPLOY_USER"
fi

log "Creando carpetas de la app y datos"
mkdir -p "$APP_DIR" "$APP_DIR/.data/uploads/products" /var/log/peninsula \
  /var/www/letsencrypt /var/backups/peninsula
chown -R "$DEPLOY_USER:www-data" "$APP_DIR" /var/log/peninsula /var/backups/peninsula
chmod 750 "$APP_DIR/.data"

log "Firewall UFW (solo 22/80/443)"
ufw allow OpenSSH
ufw allow 'Nginx Full'
ufw --force enable
ufw status verbose

log "Fail2ban (protección SSH y nginx)"
cat >/etc/fail2ban/jail.local <<'EOF'
[DEFAULT]
bantime  = 1h
findtime = 10m
maxretry = 5

[sshd]
enabled = true

[nginx-http-auth]
enabled = true

[nginx-limit-req]
enabled = true
EOF
systemctl enable fail2ban
systemctl restart fail2ban

log "Configurando PM2 para arrancar al boot (como $DEPLOY_USER)"
env PATH="$PATH:/usr/bin" pm2 startup systemd -u "$DEPLOY_USER" --hp "/home/$DEPLOY_USER" || true

cat <<EOF

\033[1;32m✔ Servidor preparado.\033[0m

PENDIENTE MANUAL (seguridad SSH — hazlo tú para no perder acceso):
  1) Copia tu clave pública:   ssh-copy-id $DEPLOY_USER@<IP-del-VPS>
  2) Edita /etc/ssh/sshd_config y deja:
         PasswordAuthentication no
         PermitRootLogin no
     Luego:  sudo systemctl restart ssh
  3) Verifica que entras como '$DEPLOY_USER' con tu clave ANTES de cerrar la sesión root.

Siguiente paso: subir el código y desplegar (ver deploy/DEPLOY.md, sección 4).
EOF
