#!/bin/bash
# Paper Dynasty - Manual Deployment Script
#
# Usage: ./deploy.sh [version]
# Example: ./deploy.sh v1.8.1
#
# This script provides a safe, manual way to deploy Paper Dynasty
# with proper checks and rollback capability.

set -e

VERSION=${1:-latest}
SERVER="sba-bots"
SERVER_IP="10.10.0.88"
DEPLOY_PATH="/home/cal/container-data/paper-dynasty"

echo "🚀 Deploying Paper Dynasty ${VERSION} to production"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

# Pre-deployment checks
echo ""
echo "📋 Pre-deployment checks..."

# Check SSH connection
if ! ssh cal@${SERVER_IP} "echo 'SSH OK'" > /dev/null 2>&1; then
    echo "❌ Cannot connect to ${SERVER}"
    exit 1
fi
echo "✅ SSH connection OK"

# Check if container exists
if ! ssh cal@${SERVER_IP} "cd ${DEPLOY_PATH} && docker compose ps" > /dev/null 2>&1; then
    echo "❌ Cannot find Paper Dynasty container on ${SERVER}"
    exit 1
fi
echo "✅ Container found"

# Confirm deployment
echo ""
echo "⚠️  This will restart the Paper Dynasty bot (brief downtime)"
read -p "Continue with deployment? (y/N) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "❌ Deployment cancelled"
    exit 1
fi

# Deploy
echo ""
echo "📥 Pulling image manticorum67/paper-dynasty:${VERSION}..."
ssh cal@${SERVER_IP} << EOF
    cd ${DEPLOY_PATH}

    # Pull new image
    docker compose pull

    # Stop old container
    echo "🛑 Stopping container..."
    docker compose down

    # Start new container
    echo "▶️  Starting container..."
    docker compose up -d

    # Wait for startup
    sleep 5

    # Check status
    echo ""
    echo "📊 Container status:"
    docker compose ps

    echo ""
    echo "📝 Recent logs:"
    docker compose logs --tail 20
EOF

echo ""
echo "✅ Deployment complete!"
echo ""
echo "To check logs: ssh ${SERVER} 'cd ${DEPLOY_PATH} && docker compose logs -f'"
echo "To rollback: ssh ${SERVER} 'cd ${DEPLOY_PATH} && docker compose down && docker compose up -d'"
