#!/usr/bin/env bash
set -e

echo "=== L2 server bootstrap for Ubuntu 24.04 ==="

# ---- check root ----
if [[ "$EUID" -ne 0 ]]; then
  echo "ERROR: run this script with sudo"
  exit 1
fi

# ---- variables ----
TARGET_USER="madvedo"

# ---- update system ----
echo "[1/7] Updating system..."
apt update -y
apt upgrade -y

# ---- base tools ----
echo "[2/7] Installing base tools..."
apt install -y \
  vim \
  curl \
  wget \
  ca-certificates \
  gnupg \
  lsb-release \
  unzip \
  unrar \
  net-tools \
  htop \
  mc

# ---- docker install ----
echo "[3/7] Installing Docker..."

if ! command -v docker >/dev/null 2>&1; then
  curl -fsSL https://get.docker.com | sh
else
  echo "Docker already installed"
fi

# ---- docker compose v2 ----
echo "[4/7] Installing docker-compose plugin..."

if ! docker compose version >/dev/null 2>&1; then
  mkdir -p /usr/local/lib/docker/cli-plugins
  curl -SL https://github.com/docker/compose/releases/latest/download/docker-compose-linux-x86_64 \
    -o /usr/local/lib/docker/cli-plugins/docker-compose
  chmod +x /usr/local/lib/docker/cli-plugins/docker-compose
else
  echo "Docker Compose already installed"
fi

# ---- enable docker ----
systemctl enable docker
systemctl start docker

# ---- add user to docker group ----
echo "[5/7] Adding user '$TARGET_USER' to docker group..."

if id "$TARGET_USER" >/dev/null 2>&1; then
  usermod -aG docker "$TARGET_USER"
else
  echo "WARNING: user $TARGET_USER does not exist"
fi

# ---- nginx ----
echo "[6/7] Installing nginx..."
apt install -y nginx
systemctl enable nginx
systemctl start nginx

# ---- final info ----
echo "[7/7] Done."

echo ""
echo "================================================="
echo " Bootstrap completed successfully"
echo ""
echo " Installed:"
echo "  - vim, unzip, unrar"
echo "  - docker + docker compose"
echo "  - nginx"
echo ""
echo " IMPORTANT:"
echo "  - Log out and log back in to apply docker group"
echo "  - Or run: newgrp docker"
echo ""
echo " Check:"
echo "  docker --version"
echo "  docker compose version"
echo "================================================="

