#!/usr/bin/env bash
# Alterra Estates — one-time preparation of a fresh VPS.
# Supported: AlmaLinux / Rocky Linux 8–10 (default on HostGator VPS) and Ubuntu 22.04/24.04 or Debian 12.
# Run as root on the new server:   bash server-setup.sh
#
# What it does: system updates and automatic security updates, a "deploy" user that can run Docker,
# Docker Engine + Compose, a firewall that only opens SSH/HTTP/HTTPS, fail2ban against SSH brute force,
# a swap file, Bogotá time zone and, only if an SSH key is already installed, disables password logins.
#
# IMPORTANT: use a VPS WITHOUT cPanel/WHM. cPanel occupies ports 80/443 and manages the firewall,
# which conflicts with this setup (Caddy serves HTTPS inside Docker).
set -euo pipefail

if [[ $EUID -ne 0 ]]; then echo "Run as root." >&2; exit 1; fi
if [[ -d /usr/local/cpanel ]]; then
  echo "cPanel/WHM is installed on this server. Ask HostGator for a VPS without cPanel (or reinstall the OS without it)." >&2
  exit 1
fi

DEPLOY_USER="${DEPLOY_USER:-deploy}"
SWAP_SIZE="${SWAP_SIZE:-2G}"
. /etc/os-release
case "${ID_LIKE:-} $ID" in
  *rhel*|*centos*|*fedora*|*almalinux*|*rocky*) FAMILY=rhel ;;
  *debian*|*ubuntu*) FAMILY=debian ;;
  *) echo "Unsupported OS: $PRETTY_NAME" >&2; exit 1 ;;
esac
echo "==> Detected $PRETTY_NAME ($FAMILY)"

echo "==> System updates, base tools and automatic security updates"
if [[ $FAMILY == rhel ]]; then
  dnf -y upgrade
  dnf -y install epel-release
  dnf -y install ca-certificates curl git tar nano firewalld fail2ban dnf-automatic dnf-plugins-core
  sed -i 's/^upgrade_type.*/upgrade_type = security/; s/^apply_updates.*/apply_updates = yes/' /etc/dnf/automatic.conf
  systemctl enable --now dnf-automatic.timer
else
  export DEBIAN_FRONTEND=noninteractive
  apt-get update -y
  apt-get upgrade -y
  apt-get install -y ca-certificates curl git nano ufw fail2ban unattended-upgrades
  dpkg-reconfigure -f noninteractive unattended-upgrades
fi
timedatectl set-timezone America/Bogota

echo "==> Docker Engine + Compose (official repository)"
if ! command -v docker >/dev/null; then
  if [[ $FAMILY == rhel ]]; then
    dnf config-manager --add-repo https://download.docker.com/linux/rhel/docker-ce.repo
    dnf -y install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
  else
    install -m 0755 -d /etc/apt/keyrings
    curl -fsSL "https://download.docker.com/linux/$ID/gpg" -o /etc/apt/keyrings/docker.asc
    chmod a+r /etc/apt/keyrings/docker.asc
    echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/$ID $VERSION_CODENAME stable" \
      > /etc/apt/sources.list.d/docker.list
    apt-get update -y
    apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
  fi
fi
systemctl enable --now docker

echo "==> Deploy user"
if ! id "$DEPLOY_USER" >/dev/null 2>&1; then
  if [[ $FAMILY == rhel ]]; then useradd -m -s /bin/bash "$DEPLOY_USER"; else adduser --disabled-password --gecos "" "$DEPLOY_USER"; fi
fi
usermod -aG docker "$DEPLOY_USER"
if [[ -f /root/.ssh/authorized_keys ]]; then
  install -d -m 700 -o "$DEPLOY_USER" -g "$DEPLOY_USER" "/home/$DEPLOY_USER/.ssh"
  install -m 600 -o "$DEPLOY_USER" -g "$DEPLOY_USER" /root/.ssh/authorized_keys "/home/$DEPLOY_USER/.ssh/authorized_keys"
  command -v restorecon >/dev/null && restorecon -R "/home/$DEPLOY_USER/.ssh" || true
fi

echo "==> Swap ($SWAP_SIZE) so builds do not run out of memory"
if ! swapon --show | grep -q /swapfile; then
  fallocate -l "$SWAP_SIZE" /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 "==> Firewall: SSH, HTTP, HTTPS only"
SSH_PORT="$(sshd -T 2>/dev/null | awk '/^port /{print $2; exit}')"
SSH_PORT="${SSH_PORT:-22}"
if [[ $FAMILY == rhel ]]; then
  systemctl enable --now firewalld
  firewall-cmd --permanent --add-port="$SSH_PORT/tcp"
  firewall-cmd --permanent --add-service=http
  firewall-cmd --permanent --add-service=https
  firewall-cmd --permanent --add-port=443/udp
  firewall-cmd --reload
else
  ufw default deny incoming
  ufw default allow outgoing
  ufw allow "$SSH_PORT/tcp"
  ufw allow 80/tcp
  ufw allow 443/tcp
  ufw allow 443/udp
  ufw --force enable
fi

echo "==> fail2ban for SSH (port $SSH_PORT)"
mkdir -p /etc/fail2ban/jail.d
cat > /etc/fail2ban/jail.d/alterra-sshd.local <<JAIL
[sshd]
enabled = true
port = $SSH_PORT
JAIL
systemctl enable --now fail2ban
systemctl restart fail2ban

echo "==> SSH hardening"
if [[ -s "/home/$DEPLOY_USER/.ssh/authorized_keys" ]]; then
  mkdir -p /etc/ssh/sshd_config.d
  cat > /etc/ssh/sshd_config.d/90-alterra.conf <<'SSH'
PasswordAuthentication no
KbdInteractiveAuthentication no
PermitRootLogin prohibit-password
SSH
  grep -q "^Include /etc/ssh/sshd_config.d/\*.conf" /etc/ssh/sshd_config || sed -i '1i Include /etc/ssh/sshd_config.d/*.conf' /etc/ssh/sshd_config
  sshd -t
  systemctl reload sshd 2>/dev/null || systemctl reload ssh
  echo "    Password logins disabled (SSH keys only)."
else
  echo "    No SSH key found in /root/.ssh/authorized_keys: password logins left ON."
  echo "    Add your public key there and rerun this script to harden SSH."
fi

echo
echo "Done. Next, as the '$DEPLOY_USER' user (ssh -p $SSH_PORT $DEPLOY_USER@<server IP>):"
echo "  git clone <repository URL> ~/alterra && cd ~/alterra"
echo "  cp deploy/.env.production.example deploy/.env.production && nano deploy/.env.production"
echo "  ./deploy/deploy.sh"
