#!/usr/bin/env bash
# ---------------------------------------------------------------
# One-shot provisioning for a fresh Ubuntu 24.04 VPS (Contabo Cloud
# VPS 30 NVMe or similar). Run this once as root on the box:
#
#   ssh root@158.220.127.51
#   bash provision.sh
#
# Idempotent — safe to re-run. Sets up:
#   - Docker + docker compose plugin
#   - UFW firewall (22, 80, 443)
#   - Fail2ban
#   - A non-root `deploy` user with sudo
#   - Automatic security updates
#   - Swap file (if none exists)
# ---------------------------------------------------------------
set -euo pipefail

if [[ $EUID -ne 0 ]]; then
  echo "Run as root." >&2
  exit 1
fi

DEPLOY_USER="${DEPLOY_USER:-deploy}"

echo ">>> Updating base packages..."
export DEBIAN_FRONTEND=noninteractive
apt-get update -qq
apt-get upgrade -y -qq
apt-get install -y -qq \
  ca-certificates curl gnupg lsb-release \
  ufw fail2ban unattended-upgrades \
  git rsync htop tmux

echo ">>> Configuring automatic security updates..."
dpkg-reconfigure -f noninteractive unattended-upgrades

echo ">>> Creating $DEPLOY_USER user (if missing)..."
if ! id -u "$DEPLOY_USER" >/dev/null 2>&1; then
  adduser --disabled-password --gecos "OrthoGlobe deploy" "$DEPLOY_USER"
  usermod -aG sudo "$DEPLOY_USER"
  mkdir -p "/home/$DEPLOY_USER/.ssh"
  chmod 700 "/home/$DEPLOY_USER/.ssh"
  # Carry root's authorised_keys over so SSH with your existing key keeps working.
  if [[ -f /root/.ssh/authorized_keys ]]; then
    cp /root/.ssh/authorized_keys "/home/$DEPLOY_USER/.ssh/"
    chown -R "$DEPLOY_USER:$DEPLOY_USER" "/home/$DEPLOY_USER/.ssh"
    chmod 600 "/home/$DEPLOY_USER/.ssh/authorized_keys"
  fi
  # Passwordless sudo so deploy scripts can be non-interactive.
  echo "$DEPLOY_USER ALL=(ALL) NOPASSWD:ALL" \
    > "/etc/sudoers.d/90-$DEPLOY_USER"
  chmod 440 "/etc/sudoers.d/90-$DEPLOY_USER"
fi

echo ">>> Installing Docker Engine + compose plugin..."
if ! command -v docker >/dev/null 2>&1; 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
  chmod a+r /etc/apt/keyrings/docker.gpg
  . /etc/os-release
  echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu $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-buildx-plugin docker-compose-plugin
fi
usermod -aG docker "$DEPLOY_USER"

echo ">>> Configuring UFW firewall..."
ufw --force reset
ufw default deny incoming
ufw default allow outgoing
ufw allow OpenSSH
ufw allow 80/tcp
ufw allow 443/tcp
ufw allow 443/udp
echo y | ufw enable

echo ">>> Enabling Fail2ban for SSH..."
systemctl enable --now fail2ban

echo ">>> Ensuring swap exists..."
if ! swapon --show | grep -q '/'; then
  fallocate -l 2G /swapfile
  chmod 600 /swapfile
  mkswap /swapfile
  swapon /swapfile
  echo '/swapfile none swap sw 0 0' >> /etc/fstab
fi

echo ">>> Timezone + chrony..."
timedatectl set-timezone UTC || true

APP_HOME="/home/$DEPLOY_USER/orthoglobe"
mkdir -p "$APP_HOME"
chown -R "$DEPLOY_USER:$DEPLOY_USER" "$APP_HOME"

echo ""
echo "=============================================================="
echo "  Provisioning complete."
echo ""
echo "  Next steps:"
echo "   1. Log in as the deploy user:   su - $DEPLOY_USER"
echo "   2. Upload the repo to:          $APP_HOME"
echo "      (rsync from your laptop, or git clone)"
echo "   3. cp deploy/.env.production.example .env  (fill in secrets)"
echo "   4. Point orthoglobe.org + www.orthoglobe.org A records"
echo "      at this server's public IPv4."
echo "   5. docker compose -f docker-compose.production.yml up -d --build"
echo ""
echo "  Caddy will auto-issue an HTTPS certificate on first start."
echo "=============================================================="
