#!/bin/bash
set -e

# WHOOSH Docker Swarm Deployment Script
# Following CHORUS deployment patterns with SHHH secret management

VERSION=${1:-v0.1.7}
REGISTRY_HOST=registry.home.deepblack.cloud

echo "🎭 WHOOSH Swarm Deployment - Version: $VERSION"

# Get build information
COMMIT_HASH=$(git rev-parse --short HEAD 2>/dev/null || echo "unknown")
BUILD_DATE=$(date -u +"%Y-%m-%dT%H:%M:%SZ")

# Build and push image
echo "📦 Building WHOOSH image..."
echo "   Version: $VERSION"
echo "   Commit: $COMMIT_HASH"
echo "   Build Date: $BUILD_DATE"

docker build \
    --build-arg VERSION=$VERSION \
    --build-arg COMMIT_HASH=$COMMIT_HASH \
    --build-arg BUILD_DATE="$BUILD_DATE" \
    -t $REGISTRY_HOST/whoosh:$VERSION \
    -t $REGISTRY_HOST/whoosh:latest \
    .

echo "🚀 Pushing to registry..."
docker push $REGISTRY_HOST/whoosh:$VERSION
docker push $REGISTRY_HOST/whoosh:latest

# Update image version in swarm compose file
sed -i "s|image: $REGISTRY_HOST/whoosh:.*|image: $REGISTRY_HOST/whoosh:$VERSION|" docker-compose.swarm.yml

echo "🔐 Checking Docker Swarm secrets..."

# Create secrets if they don't exist
secrets=(
    "whoosh_db_password"
    "gitea_token" 
    "whoosh_webhook_token"
    "whoosh_jwt_secret"
    "whoosh_service_tokens"
    "whoosh_redis_password"
)

for secret in "${secrets[@]}"; do
    if ! docker secret ls --filter name=$secret --format "{{.Name}}" | grep -q "^$secret$"; then
        echo "⚠️  Secret '$secret' not found. Please create it first:"
        echo "   echo 'your_secret_value' | docker secret create $secret -"
        exit 1
    else
        echo "✅ Secret '$secret' exists"
    fi
done

echo "📁 Creating volume directories..."
sudo mkdir -p /rust/containers/WHOOSH/{postgres,redis}
sudo chown -R 999:999 /rust/containers/WHOOSH/postgres  # postgres user
sudo chown -R 999:999 /rust/containers/WHOOSH/redis     # redis user

echo "🔄 Deploying WHOOSH stack..."
docker stack deploy -c docker-compose.swarm.yml whoosh

echo "⏰ Waiting for services to start..."
sleep 10

echo "📊 Service status:"
docker service ls --filter label=com.docker.stack.namespace=whoosh

echo "🌐 WHOOSH deployed successfully!"
echo "   - API: https://whoosh.chorus.services"
echo "   - Health: https://whoosh.chorus.services/health"
echo "   - Ready: https://whoosh.chorus.services/health/ready"

echo "📝 Monitor logs with:"
echo "   docker service logs -f whoosh_whoosh"
