#!/bin/bash
# Setup script for AppAIBuildTest deployment
# Run this on the webserver (192.168.1.43)

set -e

echo "==================================="
echo "Setting up AppAIBuildTest on server"
echo "==================================="

# Create TEST directories
echo "Creating TEST environment directories..."
sudo mkdir -p /opt/appaibuiltest-test/app
sudo chown -R dotnet-service:dotnet-service /opt/appaibuiltest-test

# Install TEST systemd service
echo "Installing TEST systemd service..."
sudo cp systemd/appaibuiltest-test.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable appaibuiltest-test
echo "✓ TEST service installed: appaibuiltest-test"

# Create PROD directories
echo "Creating PROD environment directories..."
sudo mkdir -p /opt/appaibuiltest/app
sudo chown -R dotnet-service:dotnet-service /opt/appaibuiltest

# Install PROD systemd service
echo "Installing PROD systemd service..."
sudo cp systemd/appaibuiltest.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable appaibuiltest
echo "✓ PROD service installed: appaibuiltest"

# Configure Caddy via API
echo ""
echo "Configuring Caddy reverse proxy via API..."

# Function to add route via Caddy API
add_caddy_route() {
    local domain=$1
    local port=$2
    local env_name=$3
    
    # Check if route already exists
    if curl -s http://localhost:2019/config/apps/http/servers/srv0/routes | grep -q "$domain"; then
        echo "⚠ $env_name route ($domain) already exists - skipping"
    else
        echo "Adding $env_name route: $domain -> 127.0.0.1:$port"
        curl -X POST "http://localhost:2019/config/apps/http/servers/srv0/routes/0" \
            -H "Content-Type: application/json" \
            -d "{
                \"@id\": \"${domain//./_}\",
                \"match\": [{\"host\": [\"$domain\"]}],
                \"handle\": [{
                    \"handler\": \"reverse_proxy\",
                    \"upstreams\": [{\"dial\": \"127.0.0.1:$port\"}]
                }]
            }" >/dev/null 2>&1
        
        if [ $? -eq 0 ]; then
            echo "✓ $env_name route added successfully"
        else
            echo "✗ Failed to add $env_name route - add manually to Caddyfile"
        fi
    fi
}

# Add TEST environment route
add_caddy_route "test-appaibuiltest.jarjarbinks" "5100" "TEST"

# Add PROD environment route
add_caddy_route "appaibuiltest.jarjarbinks" "5200" "PROD"

echo ""

echo "==================================="
echo "Setup complete!"
echo "==================================="
echo "TEST service: appaibuiltest-test"
echo "TEST folder: /opt/appaibuiltest-test/app"
echo "TEST URL: http://test-appaibuiltest.jarjarbinks"
echo "PROD service: appaibuiltest"
echo "PROD folder: /opt/appaibuiltest/app"
echo "PROD URL: http://appaibuiltest.jarjarbinks"
echo "==================================="