#!/usr/bin/env bash
# Install nginx site + origin SSL for ArvanCloud CDN. Run on server as root.
set -euo pipefail

APP_DIR="/srv/nodecloud/apps/biztaghavisite"
CONF_SRC="$APP_DIR/nginx/biztaghavi.conf"
CONF_DST="/etc/nginx/sites-available/biztaghavi"

if [[ ! -f "$CONF_SRC" ]]; then
  echo "ERROR: $CONF_SRC not found. git pull first."
  exit 1
fi

if [[ ! -f /etc/ssl/certs/nodecloud-selfsigned.crt ]]; then
  echo "ERROR: /etc/ssl/certs/nodecloud-selfsigned.crt missing (NODE Cloud self-signed cert)."
  exit 1
fi

echo "==> Install nginx config"
cp "$CONF_SRC" "$CONF_DST"
ln -sf "$CONF_DST" /etc/nginx/sites-enabled/biztaghavi

echo "==> Test and reload nginx"
nginx -t
systemctl reload nginx

echo "==> Origin checks"
curl -sf -o /dev/null -w "HTTP :80  → %{http_code}\n" -H "Host: biztaghavi.com" http://127.0.0.1/
curl -skf -o /dev/null -w "HTTPS :443 → %{http_code}\n" -H "Host: biztaghavi.com" https://127.0.0.1/

echo ""
echo "Done. In ArvanCloud: SSL = Full, origin = 193.105.234.35, then purge cache."
echo "Test: curl -sI https://biztaghavi.com/admin/login"
