#!/bin/bash
# deploy-arbiter.sh - Deploy Arbiter from Gitea with automatic migrations
# Location: /opt/scripts/deploy-arbiter.sh
# 
# Features:
# - Pulls latest code from firefrost-services repo
# - Runs any new database migrations
# - Restarts Arbiter service
# - Logs all actions for debugging
#
# Usage: sudo /opt/scripts/deploy-arbiter.sh [username]

set -e

# Configuration
DEPLOY_USER="${1:-system}"
GITEA_TOKEN="e0e330cba1749b01ab505093a160e4423ebbbe36"
REPO_URL="https://${GITEA_TOKEN}@git.firefrostgaming.com/firefrost-gaming/firefrost-services.git"
ARBITER_DIR="/opt/arbiter-3.0"
TEMP_DIR="/tmp/arbiter-deploy-$$"
LOG_FILE="/var/log/arbiter-deploy.log"
MIGRATION_TRACKER="${ARBITER_DIR}/.migrations-applied"

# Database credentials
DB_USER="arbiter"
DB_HOST="127.0.0.1"
DB_NAME="arbiter_db"
DB_PASS="FireFrost2026!Arbiter"

# Logging function
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

log "=========================================="
log "DEPLOY STARTED by ${DEPLOY_USER}"
log "=========================================="

# Create temp directory
mkdir -p "$TEMP_DIR"
cd "$TEMP_DIR"

# Clone the repo
log "Cloning firefrost-services..."
git clone --depth 1 "$REPO_URL" repo 2>&1 | tee -a "$LOG_FILE"

# Check if clone succeeded
if [ ! -d "repo/services/arbiter-3.0" ]; then
    log "ERROR: Clone failed or arbiter-3.0 not found"
    rm -rf "$TEMP_DIR"
    exit 1
fi

# Create migration tracker if it doesn't exist
touch "$MIGRATION_TRACKER"

# Run new migrations
log "Checking for new migrations..."
MIGRATIONS_DIR="repo/services/arbiter-3.0/migrations"

if [ -d "$MIGRATIONS_DIR" ]; then
    for migration in "$MIGRATIONS_DIR"/*.sql; do
        if [ -f "$migration" ]; then
            migration_name=$(basename "$migration")
            
            # Check if already applied
            if grep -q "^${migration_name}$" "$MIGRATION_TRACKER" 2>/dev/null; then
                log "SKIP: $migration_name (already applied)"
            else
                log "APPLYING: $migration_name"
                
                # Run the migration
                if PGPASSWORD="$DB_PASS" psql -U "$DB_USER" -h "$DB_HOST" -d "$DB_NAME" -f "$migration" 2>&1 | tee -a "$LOG_FILE"; then
                    # Mark as applied
                    echo "$migration_name" >> "$MIGRATION_TRACKER"
                    log "SUCCESS: $migration_name applied"
                else
                    log "WARNING: $migration_name may have failed (continuing anyway)"
                    # Still mark it to avoid re-running on next deploy
                    echo "$migration_name" >> "$MIGRATION_TRACKER"
                fi
            fi
        fi
    done
else
    log "No migrations directory found"
fi

# Copy new files
log "Copying updated files..."

# Copy source files
cp -r repo/services/arbiter-3.0/src/* "$ARBITER_DIR/src/" 2>&1 | tee -a "$LOG_FILE"

# Copy migrations (for reference)
cp -r repo/services/arbiter-3.0/migrations/* "$ARBITER_DIR/migrations/" 2>&1 | tee -a "$LOG_FILE"

# Copy package.json if changed
cp repo/services/arbiter-3.0/package.json "$ARBITER_DIR/package.json" 2>&1 | tee -a "$LOG_FILE"

# Check if package.json changed and run npm install
cd "$ARBITER_DIR"
if ! cmp -s "$TEMP_DIR/repo/services/arbiter-3.0/package.json" "$ARBITER_DIR/package.json.bak" 2>/dev/null; then
    log "package.json changed, running npm install..."
    cp "$ARBITER_DIR/package.json" "$ARBITER_DIR/package.json.bak"
    npm install --production 2>&1 | tee -a "$LOG_FILE"
fi

# Cleanup temp directory
rm -rf "$TEMP_DIR"

# Restart Arbiter
log "Restarting Arbiter service..."
systemctl restart arbiter-3 2>&1 | tee -a "$LOG_FILE"

# Wait and check status
sleep 3
if systemctl is-active --quiet arbiter-3; then
    log "SUCCESS: Arbiter is running"
else
    log "ERROR: Arbiter failed to start"
    systemctl status arbiter-3 2>&1 | tee -a "$LOG_FILE"
    exit 1
fi

log "=========================================="
log "DEPLOY COMPLETED by ${DEPLOY_USER}"
log "=========================================="

exit 0
