#!/bin/bash

# Example usage:
# updateConfigOption "CFG_TRAEFIK_USER" "RANDOMIZEDPASSWORD2"                      # New way (auto-discover)

updateConfigOption()
{
    local config_option="$1"
    local config_value="$2"
    local config_file="$3"

    # If no config file provided, auto-discover it
    if [[ -z "$config_file" ]]; then
        config_file=$(findConfigFileForOption "$config_option")
        if [[ $? -ne 0 || -z "$config_file" ]]; then
            isNotice "Config option '$config_option' not found in any config file"
        fi
    fi

    # SOH delimiter so values containing `|`, `/` etc. don't break sed.
    local DELIM=$'\x01'
    # Escape chars special to sed's replacement half (\ and &) AND escape any
    # literal `"` in the value, since we always wrap the result in double
    # quotes below. Without the quoting, values like the port descriptor
    # `app|webui|random:8080|...` get rewritten unquoted; sourcing the file
    # then parses each `|` as a pipeline and fails with `webui: command not
    # found`, etc.
    local escaped_value
    escaped_value=$(printf '%s' "$config_value" | sed -e 's/[\\&"]/\\&/g')

    # Check if config option exists in the file
    if grep -q "^$config_option=" "$config_file"; then
        # Extract the comment part first (everything after the first #)
        local original_line=$(grep "^$config_option=" "$config_file")
        local comment_part=$(echo "$original_line" | sed -n "s|^$config_option=[^#]*\(#.*\)|\1|p")

        # Replace the value, preserving comment if it existed. Always quoted.
        if [[ -n "$comment_part" ]]; then
            sed -i "s${DELIM}^${config_option}=.*${DELIM}${config_option}=\"${escaped_value}\"                     ${comment_part}${DELIM}" "$config_file"
        else
            sed -i "s${DELIM}^${config_option}=.*${DELIM}${config_option}=\"${escaped_value}\"${DELIM}" "$config_file"
        fi
        checkSuccess "Updated $config_option to $config_value"
        source "$config_file"
    else
        isNotice "Unable to find $config_option with value in $config_file"
    fi
}
