#!/bin/bash
set -e

# Deploy Static Files Script voor EveAI
# File: k8s/deploy-static-files.sh

ENVIRONMENT=${1:-dev}
DRY_RUN=${2}

# Configuratie
REMOTE_HOST="minty.ask-eve-ai-local.com"
BUILD_DIR="nginx/static"
CLUSTER_CONTEXT="kind-eveai-${ENVIRONMENT}-cluster"
NAMESPACE="eveai-${ENVIRONMENT}"

echo "🚀 Deploying static files to ${ENVIRONMENT} cluster on ${REMOTE_HOST}..."

# Check if build exists
if [ ! -d "$BUILD_DIR" ]; then
    echo "❌ Build directory $BUILD_DIR not found."
    echo "   Please run: cd nginx && npm run build && cd .."
    exit 1
fi

# Show what will be deployed
echo "📦 Static files to deploy:"
du -sh "$BUILD_DIR"
find "$BUILD_DIR" -type f | wc -l | xargs echo "   Files:"

if [ "$DRY_RUN" = "--dry-run" ]; then
    echo "🔍 DRY RUN - would deploy to $ENVIRONMENT cluster"
    exit 0
fi

# Deploy via direct rsync to access pod
echo "🚀 Deploying via rsync to $REMOTE_HOST:3873..."
rsync -av --delete "$BUILD_DIR/" "rsync://$REMOTE_HOST:3873/static/"

echo "✅ Static files deployed to cluster"

# Optional: Restart nginx pods to clear caches
echo "🔄 Restarting nginx pods..."
ssh "$REMOTE_HOST" "kubectl --context=$CLUSTER_CONTEXT rollout restart deployment/static-files -n $NAMESPACE"

echo "✅ Deployment completed successfully!"