#!/bin/bash
# deploy.sh - Deploy GnommoEditor to VPS via rsync

set -e

# Configuration
SERVER="${DEPLOY_SERVER:-root@76.13.144.52}"
REMOTE_DIR="${DEPLOY_DIR:-/opt/gnommoeditor}"

# Refuse to run on the production server itself
TARGET_HOST=$(echo ${SERVER} | sed 's/.*@//')
OWN_IP=$(curl -sf --max-time 3 ifconfig.me 2>/dev/null || echo "unknown")
if [ "$OWN_IP" = "$TARGET_HOST" ]; then
    echo "Error: deploy.sh must be run from your local machine, not the server."
    exit 1
fi

echo "==> Deploying to ${SERVER}:${REMOTE_DIR}"

# Sync source files
echo "==> Syncing files..."
rsync -avz --delete \
  --exclude 'node_modules' \
  --exclude 'backend/node_modules' \
  --exclude '.git' \
  --exclude 'dist' \
  --exclude '.env' \
  --exclude '.env.local' \
  --exclude '.env.prod' \
  --exclude '.DS_Store' \
  ./ ${SERVER}:${REMOTE_DIR}/

# Ensure the gnommoeditor database exists in the shared postgres instance
echo "==> Ensuring gnommoeditor database exists..."
ssh ${SERVER} "docker exec gnommo-db psql -U \$(grep ^POSTGRES_USER ${REMOTE_DIR}/.env.prod | cut -d= -f2) -c 'CREATE DATABASE gnommoeditor;' 2>/dev/null || true"

# Build and restart containers
echo "==> Building and restarting containers..."
ssh ${SERVER} "cd ${REMOTE_DIR} && docker compose -f docker-compose.prod.yml --env-file .env.prod up -d --build"

# Wait for backend to be ready
echo "==> Waiting for backend to start..."
sleep 5

# Run database migrations
echo "==> Running database migrations..."
ssh ${SERVER} "cd ${REMOTE_DIR} && docker compose -f docker-compose.prod.yml --env-file .env.prod exec -T backend npm run migrate:up"

echo "==> Done! GnommoEditor should be live at https://editor.glitch.university"
