#!/usr/bin/env bash
# VM124 bootstrap — Docker, users, firewall (Spec 034 Fase 0)
# Run as root on fresh Ubuntu 24.04 VM (2 vCPU · 4 GB RAM).
set -euo pipefail

DESK_PASSWORD="${DESK_PASSWORD:-805353}"
HOSTNAME="${HOSTNAME:-vm124-nextcloud-ligbox}"

echo "==> Users 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 (4 GB 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 "==> Base packages"
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 jq

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

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 "==> SSH password auth (cloud-init override)"
mkdir -p /etc/ssh/sshd_config.d
echo 'PasswordAuthentication yes' > /etc/ssh/sshd_config.d/60-cloudimg-settings.conf
systemctl restart ssh

echo "==> UFW"
ufw allow OpenSSH
ufw allow 8080/tcp comment 'Nextcloud HTTP (Traefik backend)'
ufw --force enable || true

hostnamectl set-hostname "$HOSTNAME" 2>/dev/null || true
echo "Bootstrap concluído: $HOSTNAME"
