#!/usr/bin/env bash
# VM123 bootstrap — users, swap, docker, fail2ban (Spec 024)
# Executar como root na VM123 recém-instalada (Ubuntu 24.04).
set -euo pipefail

DESK_PASSWORD="${DESK_PASSWORD:-805353}"

echo "==> Utilizadores mini, admin, root"
id mini &>/dev/null || useradd -m -s /bin/bash mini
id admin &>/dev/null || useradd -m -s /bin/bash admin
usermod -aG sudo admin 2>/dev/null || true
echo "mini:${DESK_PASSWORD}" | chpasswd
echo "admin:${DESK_PASSWORD}" | chpasswd
echo "root:${DESK_PASSWORD}" | chpasswd

echo "==> Swap 2G (piloto 4GB RAM)"
if ! swapon --show | grep -q swapfile; then
  fallocate -l 2G /swapfile || dd if=/dev/zero of=/swapfile bs=1M count=2048
  chmod 600 /swapfile
  mkswap /swapfile
  swapon /swapfile
  grep -q '/swapfile' /etc/fstab || echo '/swapfile none swap sw 0 0' >> /etc/fstab
fi

echo "==> Pacotes base"
export DEBIAN_FRONTEND=noninteractive
apt-get update -qq
apt-get install -y -qq curl wget git ufw fail2ban unattended-upgrades \
  apt-transport-https ca-certificates gnupg lsb-release

echo "==> Docker"
if ! command -v docker &>/dev/null; then
  install -m 0755 -d /etc/apt/keyrings
  curl -fsSL https://download.docker.com/linux/ubuntu/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/ubuntu $(. /etc/os-release && echo "$VERSION_CODENAME") stable" \
    > /etc/apt/sources.list.d/docker.list
  apt-get update -qq
  apt-get install -y -qq docker-ce docker-ce-cli containerd.io docker-compose-plugin
fi
usermod -aG docker admin 2>/dev/null || true
usermod -aG docker mini 2>/dev/null || true

echo "==> fail2ban sshd"
cat > /etc/fail2ban/jail.local <<'EOF'
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 5
bantime = 3600
findtime = 600
EOF
systemctl enable fail2ban
systemctl restart fail2ban

echo "==> UFW básico"
ufw allow OpenSSH
ufw allow 80/tcp
ufw allow 443/tcp
ufw allow 2083/tcp comment 'OpenPanel user'
ufw allow 2087/tcp comment 'OpenAdmin' from 10.10.10.0/24
ufw --force enable || true

echo "==> Wazuh agent (VM104) — instalar manualmente se o manager estiver activo:"
echo "    curl -so wazuh-agent.deb https://packages.wazuh.com/4.x/apt/pool/main/w/wazuh-agent/wazuh-agent_4.9.2-1_amd64.deb"
echo "    WAZUH_MANAGER=10.10.10.104 dpkg -i wazuh-agent.deb"

hostnamectl set-hostname vm123-finance 2>/dev/null || true
echo "Bootstrap VM123 concluído."
