#!/usr/bin/env bash
#
# One-time setup on a fresh DigitalOcean Ubuntu droplet (4 GB).
# Run as root from project root: sudo bash scripts/setup_droplet_first_time.sh
#
# Does: install Node 20, Python venv deps, nginx, MySQL client; create venv and
#       install Python deps; install systemd units (nextjs, fastapi); deploy nginx.
# You must: clone or upload repo to /var/www/boundary-fastapiandnextjs, create
#           .env (copy .env.example), create MySQL DB and run landing migration,
#           then deploy Next.js (build locally + unpack_and_start_nextjs.sh).
#
set -e

APP_ROOT="${APP_ROOT:-/var/www/boundary-fastapiandnextjs}"
cd "$APP_ROOT"

echo "=============================================="
echo "  First-time setup: DigitalOcean 4GB droplet"
echo "  APP_ROOT=$APP_ROOT"
echo "=============================================="
echo ""

# System packages
echo "[1/6] Installing system packages..."
apt-get update -qq
apt-get install -y python3 python3-venv python3-pip nginx mysql-client git curl

# Node 20
if ! command -v node &>/dev/null || [ "$(node -v | cut -d. -f1 | tr -d v)" -lt 20 ]; then
  echo "[2/6] Installing Node.js 20..."
  curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
  apt-get install -y nodejs
else
  echo "[2/6] Node.js already >= 20: $(node -v)"
fi

# Python venv and deps
echo "[3/6] Creating venv and installing Python deps..."
python3 -m venv venv
./venv/bin/pip install -q -r requirements.txt
./venv/bin/pip install -q gunicorn "uvicorn[standard]"

# Systemd units
echo "[4/6] Installing systemd units (nextjs, fastapi)..."
cp scripts/nextjs.service /etc/systemd/system/nextjs.service
cp scripts/fastapi.service /etc/systemd/system/fastapi.service
systemctl daemon-reload
systemctl enable nextjs fastapi

# Nginx
echo "[5/6] Deploying nginx config..."
bash scripts/deploy_nginx_504_fix.sh

echo "[6/6] Done."
echo ""
echo "Next steps:"
echo "  1. cp .env.example .env && nano .env   # set AUTH_SECRET_KEY, DB_*"
echo "  2. Create MySQL DB and run: mysql ... < scripts/sql/landing_content_tables.sql"
echo "  3. sudo systemctl start fastapi"
echo "  4. Deploy Next.js: build locally with scripts/build_nextjs_artifact.sh,"
echo "     upload nextjs-standalone.tar.gz, then: sudo bash scripts/unpack_and_start_nextjs.sh"
echo "  5. sudo bash scripts/check_502_upstreams.sh"
echo ""
echo "See docs/DEPLOY_DIGITALOCEAN.md for full steps."
