#!/bin/bash
# Migration script to assign unique gateway ports to existing Hermes instances

echo "Starting gateway port migration..."

# Get the database password from .env
DB_PASS=$(grep "^POSTGRES_PASSWORD=" .env | cut -d'=' -f2)
DB_CONTAINER="wakelaicom-postgres-1"

# Query to get instances that need gateway ports
QUERY="SELECT id, slug, deploy_payload FROM instances WHERE app_type = 'hermes' AND status != 'DELETED' AND deploy_payload IS NOT NULL;"

# Get instances from database
INSTANCES=$(docker exec -e PGPASSWORD="$DB_PASS" "$DB_CONTAINER" psql -h 127.0.0.1 -U wakelai -d wakelai -t -c "$QUERY")

GATEWAY_PORT_START=8642
port=$GATEWAY_PORT_START

# Find ports already in use
used_ports=$(docker exec -e PGPASSWORD="$DB_PASS" "$DB_CONTAINER" psql -h 127.0.0.1 -U wakelai -d wakelai -t -c "SELECT deploy_payload->>'gatewayPort' AS port FROM instances WHERE deploy_payload->>'gatewayPort' IS NOT NULL;" | grep -E '^[0-9]+$' || echo "")

declare -A used_map
for p in $used_ports; do
    used_map[$p]=1
done

echo "Processing instances..."

# Process each instance
echo "$INSTANCES" | while read -r id slug payload; do
    if [ -z "$id" ]; then continue; fi

    # Check if instance already has gateway port
    has_port=$(docker exec -e PGPASSWORD="$DB_PASS" "$DB_CONTAINER" psql -h 127.0.0.1 -U wakelai -d wakelai -t -c "SELECT deploy_payload->>'gatewayPort' = 'null' FROM instances WHERE id = $id;" | tr -d ' ')

    if [ "$has_port" = "f" ]; then
        existing=$(docker exec -e PGPASSWORD="$DB_PASS" "$DB_CONTAINER" psql -h 127.0.0.1 -U wakelai -d wakelai -t -c "SELECT deploy_payload->>'gatewayPort' FROM instances WHERE id = $id;" | tr -d ' ')
        echo "Instance $slug already has gateway port $existing"
        continue
    fi

    # Find next available port
    while [ "${used_map[$port]}" = "1" ]; do
        ((port++))
    done

    # Update instance with gateway port
    docker exec -e PGPASSWORD="$DB_PASS" "$DB_CONTAINER" psql -h 127.0.0.1 -U wakelai -d wakelai -c "UPDATE instances SET deploy_payload = jsonb_set(deploy_payload, '{gatewayPort}', '$port'::jsonb) WHERE id = $id;"

    used_map[$port]=1
    echo "✓ Assigned gateway port $port to instance $slug"

    # Update the container
    container_name="genney-${slug}-hermes-${slug}-1"
    if docker ps --format "{{.Names}}" | grep -q "^${container_name}$"; then
        echo "  Updating container $container_name..."

        # Update config.yaml
        docker exec "$container_name" bash -c "cat > /opt/data/config.yaml << 'EOFCFG'
model:
  provider: custom
  default: gpt-4o-mini
  base_url: https://api.openai.com/v1
  custom:
    api_key_env: OPENAI_API_KEY
api_server:
  enabled: true
  host: 0.0.0.0
  port: ${port}
reasoning:
  enabled: false
  effort: none
agent:
  encrypted_content: false
EOFCFG"

        # Update .env
        docker exec "$container_name" bash -c "grep -q API_SERVER_PORT /opt/data/.env && sed -i \"s/API_SERVER_PORT=.*/API_SERVER_PORT=${port}/\" /opt/data/.env || echo \"API_SERVER_PORT=${port}\" >> /opt/data/.env"

        # Restart gateway
        docker exec "$container_name" pkill -f "hermes gateway run" || true
        sleep 1
        docker exec -d -u hermes "$container_name" hermes gateway run

        echo "  ✓ Container updated"
    fi

    ((port++))
done

echo ""
echo "Gateway port migration complete!"
echo ""
echo "Summary:"
docker exec -e PGPASSWORD="$DB_PASS" "$DB_CONTAINER" psql -h 127.0.0.1 -U wakelai -d wakelai -c "SELECT slug, status, deploy_payload->>'gatewayPort' AS gateway_port FROM instances WHERE app_type = 'hermes' AND status != 'DELETED' ORDER BY id;"
