#!/bin/bash

# WebUI config options setter for LibrePortal
# This function handles updating config files from CLI command
# Uses the robust webuiUpdateSystemConfig function

webuiSetConfigOptions() {
    local config_type="$1"
    local config_options="$2"
    
    if [[ -z "$config_type" || -z "$config_options" ]]; then
        isError " Both config type and options are required"
        echo "Usage: libreportal webui config set <type> <options>"
        echo "Example: libreportal webui config set general CFG_INSTALL_NAME=myserver|CFG_TRAEFIK_EMAIL=admin@example.com"
    fi
    
    echo "Updating $config_type configuration..."
    echo "Options: $config_options"
    
    # Convert CLI format to JSON format for webuiUpdateSystemConfig
    # CLI: CFG_INSTALL_NAME=myserver|CFG_TRAEFIK_EMAIL=admin@example.com
    # JSON: {"CFG_INSTALL_NAME": "myserver", "CFG_TRAEFIK_EMAIL": "admin@example.com"}
    
    local json_options="{"
    local first=true
    
    # Process each config option (using | as separator)
    IFS='|' read -ra options <<< "$config_options"
    for option in "${options[@]}"; do
        # Remove leading/trailing whitespace
        option=$(echo "$option" | xargs)
        
        # Parse option in format KEY=VALUE
        if [[ "$option" =~ ^([^=]+)=(.*)$ ]]; then
            local key="${BASH_REMATCH[1]}"
            local value="${BASH_REMATCH[2]}"
            
            if [ "$first" = true ]; then
                first=false
            else
                json_options+=","
            fi
            
            # Escape quotes in value and add to JSON
            local escaped_value=$(echo "$value" | sed 's/"/\\"/g')
            json_options+="\"$key\":\"$escaped_value\""
            
            echo "Adding: $key=$value"
        else
            echo "Warning: Invalid option format: $option (should be KEY=VALUE)"
        fi
    done
    
    json_options+="}"
    
    # Use the robust webuiUpdateSystemConfig function
    echo "Applying configuration changes..."
    if echo "$json_options" | webuiUpdateSystemConfig "$config_type"; then
        echo "✓ Configuration updated successfully!"
        echo "✓ WebUI JSON regenerated"
    else
        echo "✗ Failed to update configuration"
    fi
}
