#!/usr/bin/env bash
# =============================================================================
#  OrthoGlobe app bring-up — run on the server AFTER remote-provision.sh
#  and AFTER the source code has been rsynced/scp'd into $APP_HOME.
# =============================================================================
#  Builds the Next standalone bundle, runs migrations, seeds admins +
#  email templates + store data, writes the systemd unit + Caddyfile,
#  starts the service, reloads Caddy.
#
#  Run as the deploy user (not root):
#      cd /home/deploy/orthoglobe
#      bash deploy/scripts/remote-app-start.sh
# =============================================================================
set -euo pipefail

DEPLOY_USER="${DEPLOY_USER:-deploy}"
APP_HOME="/home/$DEPLOY_USER/orthoglobe"
DOMAIN_FILE="/etc/orthoglobe/domain"
DOMAIN="${DOMAIN:-$(cat "$DOMAIN_FILE" 2>/dev/null || echo "")}"
DB_ENV="/etc/orthoglobe/db.env"
APP_ENV="/etc/orthoglobe/app.env"

if [[ -z "$DOMAIN" ]]; then
  echo "DOMAIN not set and $DOMAIN_FILE empty — aborting" >&2
  exit 1
fi

cd "$APP_HOME"

log()  { printf '\n\033[1;34m>>> %s\033[0m\n' "$*"; }

# -----------------------------------------------------------------------------
# 1. Compose the full app env file if missing
# -----------------------------------------------------------------------------
if ! sudo -n test -f "$APP_ENV"; then
  log "Composing $APP_ENV"
  # Generate secrets if app.env doesn't exist yet.
  NEXTAUTH_SECRET="$(node -e "console.log(require('crypto').randomBytes(48).toString('base64url'))")"
  APPROVAL_TOKEN_SECRET="$(node -e "console.log(require('crypto').randomBytes(48).toString('base64url'))")"
  CRON_SECRET="$(node -e "console.log(require('crypto').randomBytes(32).toString('base64url'))")"

  sudo bash -c "cat > '$APP_ENV' <<ENV
# /etc/orthoglobe/app.env — consumed by the systemd unit.
# Re-run scripts/gen-secrets.ts to rotate these.

NODE_ENV=production
HOSTNAME=127.0.0.1
PORT=3000

NEXTAUTH_URL=https://$DOMAIN
NEXTAUTH_SECRET=$NEXTAUTH_SECRET
APPROVAL_TOKEN_SECRET=$APPROVAL_TOKEN_SECRET
CRON_SECRET=$CRON_SECRET

ADMIN_NOTIFY_EMAILS=atefabdo26399@gmail.com,atef@orthoglobe.org,imam@orthoglobe.org
EMAIL_FROM='OrthoGlobe <no-reply@$DOMAIN>'
RESEND_API_KEY=

NEXT_PUBLIC_SANITY_PROJECT_ID=
NEXT_PUBLIC_SANITY_DATASET=production
NEXT_PUBLIC_SANITY_API_VERSION=2026-03-01
ENV"
  sudo bash -c "cat '$DB_ENV' >> '$APP_ENV'"
  sudo chmod 640 "$APP_ENV"
  sudo chown root:"$DEPLOY_USER" "$APP_ENV"
fi

# Export everything from the app env for use in this script.
set -a
# shellcheck disable=SC1090
source "$APP_ENV"
set +a

# -----------------------------------------------------------------------------
# 2. Install deps + build
# -----------------------------------------------------------------------------
log "Installing node modules"
pnpm install --frozen-lockfile

log "Running production build"
NEXT_TELEMETRY_DISABLED=1 pnpm build

# -----------------------------------------------------------------------------
# 3. Prepare standalone bundle (static + public)
# -----------------------------------------------------------------------------
log "Wiring standalone bundle"
cp -r public .next/standalone/public 2>/dev/null || true
mkdir -p .next/standalone/.next
cp -r .next/static .next/standalone/.next/static

# Persistent uploads dir — stays put across deploys.
mkdir -p /home/"$DEPLOY_USER"/orthoglobe-uploads
rm -rf .next/standalone/public/uploads
ln -s /home/"$DEPLOY_USER"/orthoglobe-uploads .next/standalone/public/uploads

# -----------------------------------------------------------------------------
# 4. Migrations + seeds
# -----------------------------------------------------------------------------
log "Applying DB migrations"
pnpm db:migrate

log "Seeding email templates + sample content + admin roster"
pnpm db:seed:email-templates || true
pnpm db:seed:research-extras || true
pnpm db:seed:store || true
pnpm db:ensure:admins

# -----------------------------------------------------------------------------
# 5. systemd service
# -----------------------------------------------------------------------------
log "Writing systemd unit"
sudo tee /etc/systemd/system/orthoglobe.service >/dev/null <<UNIT
[Unit]
Description=OrthoGlobe Next.js site
After=network.target postgresql.service redis-server.service
Wants=postgresql.service redis-server.service

[Service]
Type=simple
User=$DEPLOY_USER
WorkingDirectory=$APP_HOME/.next/standalone
EnvironmentFile=$APP_ENV
ExecStart=/usr/bin/node $APP_HOME/.next/standalone/server.js
Restart=always
RestartSec=3
StandardOutput=journal
StandardError=journal
# Resource hygiene
LimitNOFILE=65536
# Hardening
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=read-only
ReadWritePaths=$APP_HOME $APP_HOME/.next /home/$DEPLOY_USER/orthoglobe-uploads
PrivateTmp=true
PrivateDevices=true

[Install]
WantedBy=multi-user.target
UNIT

sudo systemctl daemon-reload
sudo systemctl enable orthoglobe.service
sudo systemctl restart orthoglobe.service
sleep 2
sudo systemctl --no-pager status orthoglobe.service | head -15

# -----------------------------------------------------------------------------
# 6. Caddyfile
# -----------------------------------------------------------------------------
log "Writing Caddyfile for $DOMAIN"
sudo tee /etc/caddy/Caddyfile >/dev/null <<CADDY
{
    email atef@orthoglobe.org
}

$DOMAIN, www.$DOMAIN {
    encode zstd gzip
    reverse_proxy 127.0.0.1:3000 {
        header_up X-Real-IP {remote_host}
        header_up X-Forwarded-For {remote_host}
        header_up X-Forwarded-Proto {scheme}
    }
    header {
        Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
        X-Content-Type-Options "nosniff"
        Referrer-Policy "strict-origin-when-cross-origin"
        Permissions-Policy "camera=(), microphone=(), geolocation=()"
        -Server
    }
    log {
        output file /var/log/caddy/access.log {
            roll_size 50MiB
            roll_keep 5
        }
        format json
    }
}
CADDY

sudo mkdir -p /var/log/caddy
sudo chown -R caddy:caddy /var/log/caddy 2>/dev/null || true
sudo systemctl reload caddy || sudo systemctl restart caddy
sleep 2
sudo systemctl --no-pager status caddy | head -10

cat <<EOF

========================================================
 Deploy done. Public URLs:
   http://$DOMAIN        (redirects to HTTPS after first cert issued)
   https://$DOMAIN
   https://www.$DOMAIN

 App logs:    journalctl -u orthoglobe -f
 Caddy logs:  journalctl -u caddy -f
========================================================
EOF
