#!/bin/bash
# Arbiter 3.0 Deployment Script
# Run on Command Center: bash /opt/arbiter-3.0/deploy.sh
# Or remotely: Copy this script to server and run

set -e  # Exit on any error

REPO_URL="https://git.firefrostgaming.com/firefrost-gaming/firefrost-services.git"
TEMP_DIR="/tmp/firefrost-services-deploy-$$"
ARBITER_DIR="/opt/arbiter-3.0"
SERVICE_NAME="arbiter-3"

echo "🔥❄️ Arbiter 3.0 Deployment"
echo "=========================="

# Cleanup any old temp directories
rm -rf /tmp/firefrost-services /tmp/firefrost-services-deploy-*

# Clone fresh
echo "📥 Cloning firefrost-services..."
git clone --depth 1 "$REPO_URL" "$TEMP_DIR"

# Copy arbiter files
echo "📋 Copying Arbiter files..."
cp -r "$TEMP_DIR/services/arbiter-3.0/src/"* "$ARBITER_DIR/src/"
cp -r "$TEMP_DIR/services/arbiter-3.0/migrations/"* "$ARBITER_DIR/migrations/" 2>/dev/null || true
cp "$TEMP_DIR/services/arbiter-3.0/package.json" "$ARBITER_DIR/package.json" 2>/dev/null || true

# Check if package.json changed (need npm install)
if ! cmp -s "$TEMP_DIR/services/arbiter-3.0/package.json" "$ARBITER_DIR/package.json.bak" 2>/dev/null; then
    echo "📦 Dependencies may have changed, running npm install..."
    cd "$ARBITER_DIR"
    npm install --production
    cp "$ARBITER_DIR/package.json" "$ARBITER_DIR/package.json.bak"
fi

# Restart service
echo "🔄 Restarting $SERVICE_NAME..."
systemctl restart "$SERVICE_NAME"

# Cleanup
echo "🧹 Cleaning up..."
rm -rf "$TEMP_DIR"

# Verify
sleep 2
if systemctl is-active --quiet "$SERVICE_NAME"; then
    echo "✅ Arbiter 3.0 deployed and running!"
    echo "   Dashboard: https://discord-bot.firefrostgaming.com/admin"
else
    echo "❌ Service failed to start. Check: journalctl -u $SERVICE_NAME -n 50"
    exit 1
fi
