#!/usr/bin/env bash
# ============================================================
# BOUSLA — Ubuntu 22/24 VPS setup (run ONCE as root on the server)
# Usage: bash server-setup.sh <domain-or-ip>
# Installs: PostgreSQL 16, Node.js 20, Nginx + Certbot (HTTPS)
# Creates: DB bousla_ops + user bousla_app (prints generated password ONCE)
# ============================================================
set -euo pipefail
[ "$EUID" -eq 0 ] || { echo "Run as root (sudo bash $0)"; exit 1; }
DOMAIN="${1:?Usage: bash server-setup.sh <domain-or-ip>}"

echo "== 1) Packages =="
apt-get update -qq
apt-get install -y curl gnupg postgresql postgresql-contrib nginx certbot python3-certbot-nginx ufw
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
apt-get install -y nodejs

echo "== 2) Firewall =="
ufw allow OpenSSH >/dev/null 2>&1 || true
ufw allow 'Nginx Full' >/dev/null 2>&1 || true
ufw --force enable
# NOTE: PostgreSQL listens on 127.0.0.1 only — port 5433/5432 stay closed to internet

echo "== 3) PostgreSQL: user + database =="
systemctl enable --now postgresql
DB_PASS="$(openssl rand -hex 24)"
su - postgres -c "psql -c \"CREATE USER bousla_app WITH PASSWORD '$DB_PASS';\"" >/dev/null
su - postgres -c "createdb -O bousla_app bousla_ops"
# Safety: the app user can NEVER drop the schema of the operations database
su - postgres -c "psql -d bousla_ops -c \"REVOKE ALL ON SCHEMA public FROM PUBLIC; GRANT USAGE, CREATE ON SCHEMA public TO bousla_app;\""
echo "==================================================================="
echo "DB PASSWORD (store it NOW in the app .env — shown once):"
echo "$DB_PASS"
echo "==================================================================="

echo "== 4) App directory =="
mkdir -p /var/www/bousla
chown -R "$SUDO_USER:${SUDO_USER:-root}" /var/www/bousla 2>/dev/null || true
echo "Upload the release package to /var/www/bousla then: cd /var/www/bousla && npm ci --omit=dev"

echo "== 5) HTTPS =="
certbot --nginx -d "$DOMAIN" || echo "certbot will run again after DNS points to this server"
echo "DONE. Next: upload code, create /var/www/bousla/apps/api/.env, enable systemd services (see deploy/), then nginx site config (deploy/nginx-bousla.conf)."
