#!/usr/bin/env bash
# One-time setup of a fresh Ubuntu 24.04 VPS (Namecheap) for Passlabb. Run as root:
#   curl -fsSL <raw url of this file> | bash      or      sudo bash deploy/scripts/setup-vps.sh
# Afterwards: edit /srv/passlabb/app/.env, then run deploy/scripts/deploy.sh.
set -euo pipefail

REPO_URL="${REPO_URL:-}"           # e.g. git@github.com:you/passlabb.git (set before running)
APP_DIR=/srv/passlabb
DB_NAME=passlabb
DB_USER=passlabb

echo "==> System packages"
apt-get update
apt-get -y upgrade
apt-get -y install curl git ufw nginx postgresql postgresql-contrib unattended-upgrades fail2ban ca-certificates gnupg
dpkg-reconfigure -f noninteractive unattended-upgrades

echo "==> Node.js 22 LTS"
if ! command -v node >/dev/null || [ "$(node -v | cut -c2-3)" -lt 20 ]; then
  curl -fsSL https://deb.nodesource.com/setup_22.x | bash -
  apt-get -y install nodejs
fi

echo "==> App user and folders"
id passlabb >/dev/null 2>&1 || adduser --system --group --home "$APP_DIR" --shell /bin/bash passlabb
mkdir -p "$APP_DIR" /var/backups/passlabb
chown -R passlabb:passlabb "$APP_DIR" /var/backups/passlabb

echo "==> Code"
if [ -n "$REPO_URL" ] && [ ! -d "$APP_DIR/.git" ]; then
  sudo -u passlabb git clone "$REPO_URL" "$APP_DIR"
fi
mkdir -p "$APP_DIR/app/uploads" && chown -R passlabb:passlabb "$APP_DIR/app/uploads"

echo "==> PostgreSQL"
DB_PASS="$(openssl rand -base64 30 | tr -dc 'A-Za-z0-9' | head -c 32)"
if ! sudo -u postgres psql -tAc "SELECT 1 FROM pg_roles WHERE rolname='$DB_USER'" | grep -q 1; then
  sudo -u postgres psql -c "CREATE ROLE $DB_USER LOGIN PASSWORD '$DB_PASS'"
  sudo -u postgres createdb -O "$DB_USER" "$DB_NAME"
  NEW_DB=1
fi

echo "==> .env"
if [ -f "$APP_DIR/app/.env.example" ] && [ ! -f "$APP_DIR/app/.env" ]; then
  cp "$APP_DIR/app/.env.example" "$APP_DIR/app/.env"
  if [ "${NEW_DB:-0}" = 1 ]; then
    sed -i "s#postgres://passlabb:CHANGE_ME@#postgres://passlabb:${DB_PASS}@#" "$APP_DIR/app/.env"
  fi
  chown passlabb:passlabb "$APP_DIR/app/.env"
  chmod 600 "$APP_DIR/app/.env"
fi

echo "==> Firewall: SSH from anywhere, web only from Cloudflare"
ufw default deny incoming
ufw default allow outgoing
ufw allow OpenSSH
for ip in $(curl -fsSL https://www.cloudflare.com/ips-v4) $(curl -fsSL https://www.cloudflare.com/ips-v6); do
  ufw allow proto tcp from "$ip" to any port 80,443
done
ufw --force enable

echo "==> SSH hardening (keys only)"
if [ -s /root/.ssh/authorized_keys ] || ls /home/*/.ssh/authorized_keys >/dev/null 2>&1; then
  sed -i 's/^#\?PasswordAuthentication .*/PasswordAuthentication no/' /etc/ssh/sshd_config
  systemctl reload ssh || systemctl reload sshd || true
else
  echo "   No SSH key found: password login left on. Add your key, then set PasswordAuthentication no."
fi

echo "==> Nginx and systemd units"
if [ -d "$APP_DIR/deploy" ]; then
  cp "$APP_DIR/deploy/nginx/book.passlabb.com.conf" /etc/nginx/sites-available/
  ln -sf /etc/nginx/sites-available/book.passlabb.com.conf /etc/nginx/sites-enabled/
  rm -f /etc/nginx/sites-enabled/default
  cp "$APP_DIR"/deploy/systemd/*.service "$APP_DIR"/deploy/systemd/*.timer /etc/systemd/system/
  systemctl daemon-reload
  chmod +x "$APP_DIR"/deploy/scripts/*.sh
fi
mkdir -p /etc/ssl/passlabb && chmod 700 /etc/ssl/passlabb

echo "==> Let the passlabb user restart only its own services (used by deploy.sh)"
cat > /etc/sudoers.d/passlabb <<'SUDO'
passlabb ALL=(root) NOPASSWD: /usr/bin/systemctl restart passlabb-app.service, /usr/bin/systemctl enable --now passlabb-app.service passlabb-emails.timer passlabb-prices.timer passlabb-fx.timer passlabb-cleanup.timer passlabb-backup.timer
SUDO
chmod 440 /etc/sudoers.d/passlabb
visudo -cf /etc/sudoers.d/passlabb

cat <<MSG

Setup done. Next steps:
 1. Put the Cloudflare Origin Certificate in /etc/ssl/passlabb/origin.pem and origin.key (Cloudflare → SSL/TLS → Origin Server).
 2. Edit $APP_DIR/app/.env (APP_URL, ADMIN_NOTIFY_EMAIL, BREVO_API_KEY, SITE_DEPLOY_HOOK).
 3. sudo -u passlabb bash $APP_DIR/deploy/scripts/deploy.sh --first-run
 4. Sign in at https://book.passlabb.com/admin with amine@passlabb.com and the OWNER_PASSWORD you set in .env, then remove it from .env.
 5. sudo nginx -t && sudo systemctl reload nginx
MSG
