#!/bin/bash
# Deploy Katheryn website infrastructure to Netcup

set -e

REMOTE_HOST="netcup"
REMOTE_PATH="/opt/websites/katheryn-website"
LOCAL_PATH="/home/jeffe/Github/katheryn-website"

echo "=== Deploying Katheryn Website Infrastructure ==="

# 1. Create remote directory
echo "[1/5] Creating remote directory..."
ssh $REMOTE_HOST "mkdir -p $REMOTE_PATH/directus"

# 2. Copy Docker Compose and config files
echo "[2/5] Copying configuration files..."
scp $LOCAL_PATH/directus/docker-compose.yml $REMOTE_HOST:$REMOTE_PATH/directus/
scp $LOCAL_PATH/directus/.env.example $REMOTE_HOST:$REMOTE_PATH/directus/

# 3. Generate .env on server if it doesn't exist
echo "[3/5] Checking/generating credentials..."
ssh $REMOTE_HOST "
    if [ ! -f $REMOTE_PATH/directus/.env ]; then
        echo 'Generating secure credentials...'
        DB_PASSWORD=\$(openssl rand -base64 24 | tr -dc 'a-zA-Z0-9' | head -c 32)
        ADMIN_PASSWORD=\$(openssl rand -base64 24 | tr -dc 'a-zA-Z0-9' | head -c 24)
        DIRECTUS_SECRET=\$(openssl rand -hex 32)

        cat > $REMOTE_PATH/directus/.env << EOF
# Database
DB_USER=directus
DB_PASSWORD=\${DB_PASSWORD}
DB_DATABASE=katheryn

# Directus Admin
ADMIN_EMAIL=katheryn@katheryntrenshaw.com
ADMIN_PASSWORD=\${ADMIN_PASSWORD}

# Security
DIRECTUS_SECRET=\${DIRECTUS_SECRET}
EOF
        chmod 600 $REMOTE_PATH/directus/.env
        echo ''
        echo '========================================='
        echo 'ADMIN CREDENTIALS (SAVE THESE!):'
        echo 'Email: katheryn@katheryntrenshaw.com'
        echo \"Password: \${ADMIN_PASSWORD}\"
        echo '========================================='
    else
        echo '.env already exists, skipping generation'
    fi
"

# 4. Deploy with Docker Compose
echo "[4/5] Deploying Directus..."
ssh $REMOTE_HOST "cd $REMOTE_PATH/directus && docker compose up -d"

# 5. Wait for health check
echo "[5/5] Waiting for services to be healthy..."
ssh $REMOTE_HOST "
    echo 'Waiting for Directus to start...'
    for i in {1..30}; do
        if docker exec katheryn-cms wget -q --spider http://localhost:8055/server/health 2>/dev/null; then
            echo 'Directus is healthy!'
            exit 0
        fi
        echo 'Waiting... (\$i/30)'
        sleep 5
    done
    echo 'Warning: Health check timed out'
    docker logs katheryn-cms --tail 50
"

echo ""
echo "=== Deployment Complete ==="
echo "Directus should be available at: https://cms.katheryntrenshaw.com"
echo "(Once Cloudflare tunnel is configured)"
