#!/bin/bash
set -e

# WHOOSH Docker Swarm Secrets Setup Script

echo "🔐 Setting up WHOOSH Docker Swarm secrets..."

# Function to create or update secret
create_or_update_secret() {
    local secret_name=$1
    local secret_value=$2
    local description=$3
    
    if docker secret ls --filter name=$secret_name --format "{{.Name}}" | grep -q "^$secret_name$"; then
        echo "⚠️  Secret '$secret_name' already exists. To update, remove and recreate:"
        echo "   docker secret rm $secret_name"
        echo "   echo 'new_value' | docker secret create $secret_name -"
    else
        echo "$secret_value" | docker secret create $secret_name -
        echo "✅ Created secret: $secret_name ($description)"
    fi
}

# Generate random passwords and tokens
WHOOSH_DB_PASSWORD=$(openssl rand -base64 32)
WEBHOOK_TOKEN=$(openssl rand -hex 32)
JWT_SECRET=$(openssl rand -base64 64)
REDIS_PASSWORD=$(openssl rand -base64 32)

# Service tokens (comma-separated list)
SERVICE_TOKEN_1=$(openssl rand -hex 32)
SERVICE_TOKEN_2=$(openssl rand -hex 32)
SERVICE_TOKENS="$SERVICE_TOKEN_1,$SERVICE_TOKEN_2"

# Read GITEA token from secrets directory
if [ -f "/home/tony/chorus/business/secrets/gitea-token" ]; then
    GITEA_TOKEN=$(cat /home/tony/chorus/business/secrets/gitea-token)
    echo "📖 Using GITEA token from secrets directory"
else
    echo "❌ GITEA token not found at /home/tony/chorus/business/secrets/gitea-token"
    echo "Please ensure the token file exists before running this script."
    exit 1
fi

# Create secrets
echo ""
echo "Creating secrets..."

create_or_update_secret "whoosh_db_password" "$WHOOSH_DB_PASSWORD" "PostgreSQL database password"
create_or_update_secret "gitea_token" "$GITEA_TOKEN" "GITEA API access token"
create_or_update_secret "whoosh_webhook_token" "$WEBHOOK_TOKEN" "GITEA webhook validation token"
create_or_update_secret "whoosh_jwt_secret" "$JWT_SECRET" "JWT signing secret"
create_or_update_secret "whoosh_service_tokens" "$SERVICE_TOKENS" "Service authentication tokens"
create_or_update_secret "whoosh_redis_password" "$REDIS_PASSWORD" "Redis authentication password"

echo ""
echo "🔑 Secrets summary:"
echo "   - whoosh_db_password: ✅"
echo "   - gitea_token: ✅" 
echo "   - whoosh_webhook_token: ✅"
echo "   - whoosh_jwt_secret: ✅"
echo "   - whoosh_service_tokens: ✅ (2 tokens)"
echo "   - whoosh_redis_password: ✅"

echo ""
echo "📝 Save these service tokens for agent configuration:"
echo "   Service Token 1: $SERVICE_TOKEN_1"
echo "   Service Token 2: $SERVICE_TOKEN_2"
echo "   Webhook Token: $WEBHOOK_TOKEN"

echo ""
echo "✅ WHOOSH secrets setup complete!"
echo "You can now run: ./scripts/deploy-swarm.sh"