#!/bin/bash

# BMC Hub Production Deployment Script
# Usage: ./updateto.sh v1.3.15

set -e  # Exit on any error

VERSION=$1

if [ -z "$VERSION" ]; then
    echo "❌ Fejl: Ingen version angivet"
    echo "Usage: ./updateto.sh v1.3.15"
    exit 1
fi

# SAFETY CHECK: Verify we're on production server
CURRENT_IP=$(hostname -I | awk '{print $1}' 2>/dev/null || echo "unknown")
CURRENT_DIR=$(pwd)

if [[ "$CURRENT_IP" != "172.16.31.183" ]] && [[ "$CURRENT_DIR" != "/srv/podman/bmc_hub_v1.0" ]]; then
    echo "⚠️  ADVARSEL: Dette script skal kun køres på PRODUCTION serveren!"
    echo "   Forventet IP: 172.16.31.183"
    echo "   Forventet mappe: /srv/podman/bmc_hub_v1.0"
    echo "   Nuværende IP: $CURRENT_IP"
    echo "   Nuværende mappe: $CURRENT_DIR"
    echo ""
    read -p "Er du SIKKER på du vil fortsætte? (skriv 'JA' for at fortsætte): " CONFIRM
    if [ "$CONFIRM" != "JA" ]; then
        echo "❌ Deployment afbrudt"
        exit 1
    fi
fi

echo "🚀 Deploying BMC Hub version: $VERSION"
echo "================================"

# Check if .env exists
if [ ! -f ".env" ]; then
    echo "❌ Fejl: .env fil ikke fundet"
    exit 1
fi

# Update RELEASE_VERSION in .env
echo "📝 Opdaterer .env med version $VERSION..."
if grep -q "^RELEASE_VERSION=" .env; then
    # Replace existing line
    sed -i.bak "s/^RELEASE_VERSION=.*/RELEASE_VERSION=$VERSION/" .env
else
    # Add if missing
    echo "RELEASE_VERSION=$VERSION" >> .env
fi

echo "✅ .env opdateret"

# Stop containers
echo ""
echo "⏹️  Stopper containere..."
podman-compose -f docker-compose.prod.yml down

# Pull/rebuild with new version
echo ""
echo "🔨 Bygger nyt image med version $VERSION..."
podman-compose -f docker-compose.prod.yml up -d --build

# Sync migrations from container to host
echo ""
echo "📁 Syncer migrations fra container til host..."
if podman cp bmc-hub-api-prod:/app/migrations ./migrations_temp 2>/dev/null; then
    rm -rf ./migrations
    mv ./migrations_temp ./migrations
    chmod -R 755 ./migrations
    echo "✅ Migrations synced"
else
    echo "⚠️  Warning: Could not sync migrations (container might not be ready yet)"
fi

# Wait a bit for startup
echo ""
echo "⏳ Venter på container startup..."
sleep 5

# Show logs
echo ""
echo "📋 Logs fra startup:"
echo "================================"
podman logs --tail 50 bmc-hub-api-prod

echo ""
echo "✅ Deployment fuldført!"
echo ""
echo "🔍 Tjek status med:"
echo "   podman-compose -f docker-compose.prod.yml ps"
echo "   podman logs -f bmc-hub-api-prod"
echo ""
echo "🌐 Test health endpoint:"
echo "   curl http://localhost:8000/health"
echo ""
echo "📊 Sync kunder fra e-conomic:"
echo "   curl -X POST http://localhost:8000/api/v1/system/sync/economic"
echo ""
echo "🔗 Link vTiger til kunder:"
echo "   curl -X POST http://localhost:8000/api/v1/system/sync/vtiger"
