#!/bin/bash
# Deploy BMC Hub to production server
# Usage: ./deploy_to_prod.sh v1.3.56

set -e

VERSION=$1
PROD_SERVER="bmcadmin@172.16.31.183"
PROD_DIR="/srv/podman/bmc_hub_v1.0"

if [ -z "$VERSION" ]; then
    echo "❌ Usage: ./deploy_to_prod.sh v1.3.56"
    exit 1
fi

echo "🚀 Deploying $VERSION to production..."
echo "======================================="

# Update .env file
echo "📝 Updating RELEASE_VERSION to $VERSION..."
ssh $PROD_SERVER "sed -i 's/^RELEASE_VERSION=.*/RELEASE_VERSION=$VERSION/' $PROD_DIR/.env"

# Stop containers
echo "🛑 Stopping containers..."
ssh $PROD_SERVER "cd $PROD_DIR && podman-compose down"

# Rebuild with no cache (to pull latest version from Gitea)
echo "🔨 Building new image from version $VERSION..."
ssh $PROD_SERVER "cd $PROD_DIR && podman-compose build --no-cache"

# Start containers
echo "▶️  Starting containers..."
ssh $PROD_SERVER "cd $PROD_DIR && podman-compose up -d"

# Wait for service to be ready
echo "⏳ Waiting for service to start..."
sleep 15

# Check health
echo "🏥 Checking service health..."
HEALTH=$(curl -s http://172.16.31.183:8000/health || echo "FAILED")
if echo "$HEALTH" | grep -q "ok"; then
    echo "✅ Deployment successful!"
    echo "$HEALTH"
else
    echo "❌ Health check failed:"
    echo "$HEALTH"
    exit 1
fi

# Clean up old images (keep last 14 days)
echo "🧹 Cleaning up images older than 14 days..."
ssh $PROD_SERVER "sudo podman image prune -a -f --filter 'until=336h'"

echo ""
echo "🎉 Production is now running version $VERSION"
echo "   http://172.16.31.183:8000"
