#!/bin/bash
# neon-startup.sh — Start all neon services in dependency order.
# Run after a reboot: bash neon-startup.sh
set -euo pipefail

NEON="allaun@100.92.88.64"
SSH="ssh -o ConnectTimeout=10 $NEON"
RSYNC="rsync -az"

echo "=== 1. Postgres ==="
$SSH "podman start arxiv-pg 2>/dev/null; sleep 5"
$SSH "pg_isready -h localhost" || { echo "Postgres failed to start"; exit 1; }

echo "=== 2. Redis ==="
$SSH "
  podman rm -f redis 2>/dev/null || true
  podman run -d --name redis --network host docker.io/library/redis:7-alpine
  sleep 3
"

echo "=== 3. Database setup ==="
$SSH '
  PATH=$HOME/.nix-profile/bin:$PATH
  export PGPASSWORD=postgres

  # Create appflowy database
  psql -h localhost -U postgres -tc "SELECT 1 FROM pg_database WHERE datname='"'appflowy'"'" | grep -q 1 || \
    psql -h localhost -U postgres -c "CREATE DATABASE appflowy"

  # Set search_path
  psql -h localhost -U postgres -d appflowy -c "ALTER DATABASE appflowy SET search_path TO auth, public"
  psql -h localhost -U postgres -d appflowy -c "DROP SCHEMA IF EXISTS auth CASCADE; CREATE SCHEMA auth"
'

echo "=== 4. GoTrue migrations ==="
# Copy migration files if needed
$SSH "ls /tmp/appflowy_migrations/*.sql >/dev/null 2>&1" || \
  rsync -az /tmp/AppFlowy-Cloud/migrations/ $NEON:/tmp/appflowy_migrations/

$SSH '
  PATH=$HOME/.nix-profile/bin:$PATH
  
  for f in $(ls /tmp/appflowy_migrations/*.sql 2>/dev/null | sort); do
    ver=$(basename $f | cut -d_ -f1)
    sql=$(sed "s/{{ index .Options \"Namespace\" }}/auth/g" $f)
    PGPASSWORD=postgres psql -h localhost -U postgres -d appflowy -v ON_ERROR_STOP=1 -c "$sql" 2>/dev/null || true
  done
  echo "Migrations applied"
'

echo "=== 5. GoTrue ==="
$SSH '
  podman rm -f appflowy_gotrue_1 2>/dev/null || true
  podman run -d --name appflowy_gotrue_1 \
    --network host \
    -e GOTRUE_ADMIN_EMAIL=admin@researchstack.info \
    -e GOTRUE_ADMIN_PASSWORD=admin123 \
    -e GOTRUE_DISABLE_SIGNUP=false \
    -e GOTRUE_SITE_URL=https://researchstack.info/appflowy \
    -e GOTRUE_URI_ALLOW_LIST=** \
    -e GOTRUE_JWT_SECRET=jwt_ \
    -e GOTRUE_JWT_EXP=3600 \
    -e GOTRUE_DB_DRIVER=postgres \
    -e API_EXTERNAL_URL=https://researchstack.info/appflowy/gotrue \
    -e DATABASE_URL="postgres://postgres:postgres@localhost:5432/appflowy" \
    -e PORT=9999 \
    -e GOTRUE_MAILER_AUTOCONFIRM=true \
    -e GOTRUE_LOG_LEVEL=info \
    -e REDIS_ENABLED=true \
    -e REDIS_URL=redis://localhost:6379 \
    docker.io/appflowyinc/gotrue:0.15.1
  sleep 5
  curl -s -o /dev/null -w "%{http_code}" http://localhost:9999/health
' || { echo "GoTrue failed"; exit 1; }

echo "=== 6. AppFloyo Cloud ==="
$SSH '
  podman rm -f appflowy_cloud 2>/dev/null || true
  podman run -d --name appflowy_cloud \
    --network host \
    -e APPFLOWY_DATABASE_URL="postgres://postgres:postgres@localhost:5432/appflowy?sslmode=disable&options=-c%20search_path=public" \
    -e APPFLOWY_ENVIRONMENT=production \
    -e APPFLOWY_REDIS_URI=redis://localhost:6379 \
    -e APPFLOWY_GOTRUE_JWT_SECRET=jwt_ \
    -e APPFLOWY_GOTRUE_JWT_EXP=3600 \
    -e APPFLOWY_GOTRUE_BASE_URL=http://localhost:9999 \
    -e APPFLOWY_BASE_URL=https://researchstack.info/appflowy \
    -e APPFLOWY_WEB_URL=https://researchstack.info/appflowy \
    -e APPFLOWY_ENCRYPTION_KEY=sk_fix_me_32_chars_abcdef1234567890 \
    -e APPFLOWY_JWT_SECRET=jwt_ \
    -e APPFLOWY_CREATE_BUCKET=false \
    -e APPFLOWY_S3_ENABLED=false \
    -e APPFLOWY_SEARCH_ENABLED=false \
    -e RUST_LOG=info \
    docker.io/appflowyinc/appflowy_cloud:latest
'

echo "=== 7. Other services ==="
$SSH '
  for svc in couchdb homarr-web www-static hermes-dashboard; do
    podman start $svc 2>/dev/null || true
  done
'

echo "=== 8. Health check ==="
sleep 15
for svc in "GoTrue:9999/health" "AppFloyo:8000/api/health" "Homarr:7575/auth/login" "CouchDB:5984"; do
  name="${svc%%:*}"
  url="${svc#*:}"
  code=$($SSH "curl -s -o /dev/null -w '%{http_code}' http://localhost:$url" 2>/dev/null || echo "down")
  echo "  $name: $code"
done

echo "=== Done ==="
$SSH "tailscale status 2>/dev/null | grep neon"
