#!/bin/bash
# Arbiter 3.0 Deployment Script
# Run on Command Center: bash /opt/arbiter-3.0/deploy.sh
# Or via Trinity Console Deploy button
#
# Usage: deploy.sh [username]
#   username: Optional - who triggered the deploy (for logging)

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"
LOCKDIR="/tmp/arbiter_deploy.lock"
LOG_FILE="/var/log/trinity-deployments.log"
DEPLOY_USER="${1:-manual}"

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

# 1. Prevent concurrent deployments with a lock directory
if ! mkdir "$LOCKDIR" 2>/dev/null; then
    echo "ERROR: Deployment already in progress." >&2
    exit 1
fi
# Ensure lock is removed when script exits (success or failure)
trap 'rm -rf "$LOCKDIR"' EXIT

log "🔥❄️ Arbiter deployment started by: $DEPLOY_USER"

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

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

# Get commit info for logging
COMMIT_HASH=$(cd "$TEMP_DIR" && git log -1 --format="%h - %s")
log "📌 Deploying commit: $COMMIT_HASH"

# Copy arbiter files
log "📋 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
    log "📦 Dependencies changed, running npm install..."
    cd "$ARBITER_DIR"
    npm install --production --ignore-scripts
    cp "$ARBITER_DIR/package.json" "$ARBITER_DIR/package.json.bak"
fi

# Cleanup temp files BEFORE restart
log "🧹 Cleaning up temp files..."
rm -rf "$TEMP_DIR"

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

# Verify
sleep 2
if systemctl is-active --quiet "$SERVICE_NAME"; then
    log "✅ Arbiter deployed successfully! Commit: $COMMIT_HASH"
    echo "SUCCESS: Deployed commit $COMMIT_HASH"
else
    log "❌ Service failed to start after deploy"
    echo "ERROR: Service failed to start. Check: journalctl -u $SERVICE_NAME -n 50" >&2
    exit 1
fi
