#!/usr/bin/env bash
# Eseguire UNA VOLTA sul server con sudo (da console SSH o: sudo bash server_bootstrap.sh)
set -euo pipefail

if [[ "${EUID}" -ne 0 ]]; then
  if sudo -n true 2>/dev/null; then
    exec sudo -n bash "$0" "$@"
  else
    echo "ERRORE: eseguire come root o con sudo senza password:"
    echo "  sudo bash $0"
    echo ""
    echo "Per abilitare NOPASSWD per eminux (opzionale):"
    echo "  echo 'eminux ALL=(ALL) NOPASSWD: ALL' | sudo tee /etc/sudoers.d/eminux-nopasswd"
    exit 1
  fi
fi

export DEBIAN_FRONTEND=noninteractive

apt-get update -qq
apt-get install -y -qq ca-certificates curl git ufw rsync

if ! command -v docker >/dev/null 2>&1; then
  install -m 0755 -d /etc/apt/keyrings
  curl -fsSL https://download.docker.com/linux/debian/gpg -o /etc/apt/keyrings/docker.asc
  chmod a+r /etc/apt/keyrings/docker.asc

  . /etc/os-release
  CODENAME="${VERSION_CODENAME:-bookworm}"
  if [[ "$CODENAME" == "trixie" ]]; then
    CODENAME="bookworm"
  fi

  echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/debian ${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 eminux 2>/dev/null || true
systemctl enable --now docker

mkdir -p /opt/matchlivetv
chown -R eminux:eminux /opt/matchlivetv

# UFW base
ufw --force reset || true
ufw default deny incoming
ufw default allow outgoing
ufw allow 22/tcp comment 'SSH'
ufw allow 1935/tcp comment 'RTMP MediaMTX'
ufw allow 8888/tcp comment 'HLS MediaMTX optional'
ufw allow from 192.168.0.0/16 to any port 3000 proto tcp comment 'Rails LAN NPM'
ufw --force enable

docker --version
docker compose version
echo "Bootstrap completato. Riavvia sessione SSH di eminux per gruppo docker."
