cat << "EOF"
  ██████╗██╗  ██╗ █████╗ ███╗   ██╗ ██████╗ ███████╗
 ██╔════╝██║  ██║██╔══██╗████╗  ██║██╔════╝ ██╔════╝
 ██║     ███████║███████║██╔██╗ ██║██║  ███╗█████╗  
 ██║     ██╔══██║██╔══██║██║╚██╗██║██║   ██║██╔══╝  
 ╚██████╗██║  ██║██║  ██║██║ ╚████║╚██████╔╝███████╗
  ╚═════╝╚═╝  ╚═╝╚═╝  ╚═╝╚═╝  ╚═══╝ ╚═════╝ ╚══════╝
                                                    
 ███╗   ███╗ █████╗ ██╗  ██╗███████╗██████╗ 
 ████╗ ████║██╔══██╗██║ ██╔╝██╔════╝██╔══██╗
 ██╔████╔██║███████║█████╔╝ █████╗  ██████╔╝
 ██║╚██╔╝██║██╔══██║██╔═██╗ ██╔══╝  ██╔══██╗
 ██║ ╚═╝ ██║██║  ██║██║  ██╗███████╗██║  ██║
 ╚═╝     ╚═╝╚═╝  ╚═╝╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝
                        Post-Install Wizard

echo "Welcome to the Post-Install Wizard!"

EOF

# Update services.yaml with domain from .env
echo "Updating service configurations with domain from .env..."

ENV_FILE="/mnt/samsung500/Change Maker Dev/Changemaker/.env"
SERVICES_FILE="/mnt/samsung500/Change Maker Dev/Changemaker/configs/homepage/services.yaml"

if [ -f "$ENV_FILE" ]; then
    DOMAIN=$(grep -E "^DOMAIN=" "$ENV_FILE" | cut -d= -f2)
    
    if [ -n "$DOMAIN" ]; then
        echo "Found domain: $DOMAIN"
        
        # Update Cloudflare configuration with domain
        CLOUDFLARE_CONFIG="/mnt/samsung500/Change Maker Dev/Changemaker/example.cloudflare.config.yml"
        if [ -f "$CLOUDFLARE_CONFIG" ]; then
            echo "Updating Cloudflare configuration with domain: $DOMAIN"
            
            # Create backup of Cloudflare config file
            cp "$CLOUDFLARE_CONFIG" "${CLOUDFLARE_CONFIG}.bak"
            
            # Replace example.org with actual domain while preserving sanitized placeholders
            sed -i "s/betteredmonton\.org/$DOMAIN.org/g" "$CLOUDFLARE_CONFIG"
            
            echo "✅ Cloudflare configuration updated with domain: $DOMAIN"
            
            if [ -f "$SERVICES_FILE" ]; then
                echo "Updating services.yaml with URLs from Cloudflare config..."
                
                # Create backup of services file
                cp "$SERVICES_FILE" "${SERVICES_FILE}.bak"
                
                # Extract hostname and port mappings from Cloudflare config
                # Format: hostname -> port
                declare -A HOSTNAME_TO_PORT
                
                # Parse the Cloudflare config file to extract hostname -> port mappings
                while IFS= read -r line; do
                    if [[ $line =~ hostname:\ *([^\ ]+) ]]; then
                        hostname="${BASH_REMATCH[1]}"
                        # Read the next line which should contain the service URL with port
                        read -r service_line
                        if [[ $service_line =~ service:\ *http://localhost:([0-9]+) ]]; then
                            port="${BASH_REMATCH[1]}"
                            HOSTNAME_TO_PORT["$hostname"]="$port"
                        fi
                    fi
                done < "$CLOUDFLARE_CONFIG"
                
                # Now update the services.yaml file
                # Create a temporary file to hold the modified content
                TEMP_FILE=$(mktemp)
                
                # Use awk to find and replace href URLs in services.yaml
                awk -v domain="$DOMAIN.org" '
                BEGIN {
                    # Add all hostname->port mappings from our associative array
                    # These will be populated by the shell via environment variables
                    split("", hostnames)
                    split("", ports)
                    for (i = 1; ENVIRON["HOSTNAME_" i] != ""; i++) {
                        hostnames[i] = ENVIRON["HOSTNAME_" i]
                        ports[i] = ENVIRON["PORT_" i]
                    }
                }
                
                {
                    # If the line contains an href with a port
                    if ($0 ~ /href:.*:[0-9]+\//) {
                        for (i in hostnames) {
                            # If the line contains the port number, replace with the hostname
                            if ($0 ~ ":" ports[i] "/") {
                                # Replace the entire URL
                                sub(/href:.*/, "href: http://" hostnames[i] "/")
                                break
                            }
                        }
                    }
                    # Print the line (modified or not)
                    print $0
                }' "$SERVICES_FILE" > "$TEMP_FILE"
                
                # Export the hostname->port mappings as environment variables for awk
                idx=1
                for hostname in "${!HOSTNAME_TO_PORT[@]}"; do
                    export "HOSTNAME_$idx=$hostname"
                    export "PORT_$idx=${HOSTNAME_TO_PORT[$hostname]}"
                    ((idx++))
                done
                
                # Replace the original file with our modified version
                mv "$TEMP_FILE" "$SERVICES_FILE"
                
                # Clean up environment variables
                for ((i=1; i<=idx; i++)); do
                    unset "HOSTNAME_$i" "PORT_$i"
                done
                
                echo "✅ Services configuration updated with hostnames from Cloudflare config"
            else
                echo "❌ Services file not found: $SERVICES_FILE"
            fi
        else
            echo "❌ Cloudflare config file not found: $CLOUDFLARE_CONFIG"
        fi
    else
        echo "❌ DOMAIN value not found in .env file"
    fi
else
    echo "❌ .env file not found: $ENV_FILE"
fi

# Pull Gemma3 model from Ollama
docker exec -it ollama ollama pull gemma3

# Inform users about setting up OpenWebUI with Ollama
echo "✅ Now you can visit OpenWebUI at http://$DOMAIN:${OPEN_WEBUI_PORT:-3005} and connect it to Ollama"
echo "   Configure OpenWebUI to use the Ollama API at: http://ollama:11435"
