#!/bin/bash

set -u

LIGHTTPD_CONFIG_DIR="${LIGHTTPD_CONFIG_DIR:="/etc/lighttpd/configs"}"

# shellcheck disable=SC2016 # escaping is tricky here, because it will be called with "eval echo"
WEBSOCKET_TEMPLATE='\$HTTP["url"] == "${apiPath}" {
        wstunnel.ping-interval = 15
        wstunnel.server = ( "" => ( ( "host" => "127.0.0.1", "port" => "${innerPort}" ) ) )
        wstunnel.frame-type = "text"
    }'

# shellcheck disable=SC2016 # escaping is tricky here, because it will be called with "eval echo"
PROXY_TEMPLATE='\$HTTP["url"] =~ "(?i)^${apiPath}" {
        proxy.server = ( "" => (
            ( "host" => "127.0.0.1", "port" => "${innerPort}" )
        ) )
        proxy.header = ( "upgrade" => "enable" )
    }'

# shellcheck disable=SC2016 # escaping is tricky here, because it will be called with "eval echo"
STATICWEB_TEMPLATE='\$HTTP["url"] =~ "(?i)^${apiPath}" {
        alias.url = ("${apiPath}" => "${documentRoot}" )
    }'

# Generate single lighttpd config file
generate_lighttpd_config() {
    local static_config_file="$1"
    local output_dir="$2"
    local lighttpd_port="$3"
    # Following variables are defined by static JSON parsing:
    # protocol, name, apiPath, type, documentRoot, innerPort
    
    # Generate file name
    local number
    number=$(printf "%03d" $((900 + ${#apiPath})))
    local output_file="${output_dir}/20-lwrhttp-${lighttpd_port}-${number}-${name}.conf"
    
    if [[ -f "${output_file}" && "${output_file}" -nt "${static_config_file}" ]]; then
        #File already exists and up-to-date
        return 0;
    fi
    echo "Generate file ${output_file} from ${static_config_file}. Params: protocol=${protocol}, name=${name}, apiPath=${apiPath}, type=${type}, documentRoot=${documentRoot}, innerPort=${innerPort}"
    # Generate config based on type
    local template
    case "${type}" in
        "websocket") template="${WEBSOCKET_TEMPLATE}" ;;
        "proxy")     template="${PROXY_TEMPLATE}"     ;;
        "staticweb") template="${STATICWEB_TEMPLATE}" ;;
        *)
            echo "Error: Unknown type '${type}' in file '${static_config_file}'"
            return 1
            ;;
    esac
    # shellcheck disable=SC2016 # escaping is tricky here, because it will be called with "eval echo"
    config_template='#${apiPath}\n\
\$SERVER["socket"] == ":${lighttpd_port}" {\n\
    '${template}'\n\
}\n\
\n\
\$SERVER["socket"] == "[::]:${lighttpd_port}" {\n\
    '${template}'\n\
}\n'

    # need to escape " chars in variable
    eval "echo -e \"${config_template//\"/\\\"}\"" > "${output_file}"
    echo "Generated config file: ${output_file}"
}

# Main function to process static config file
process_static_config() {
    local file="${1}"
    if [[ ! -f "${file}" ]]; then
        echo "Error: config file not exists '${file}'"
        return 1;
    fi
    # Extract values
    local values=""
    
    # converting JSON object key-values to bash variable declare format: {"a":"b"} -> a='b'
    if ! values="$(jq -e -r 'to_entries | .[] | .key + "=" + (.value | @sh)' "${file}")"; then
        echo "Error: Failed to parse config file '${file}'"
        return 1;
    fi
    # these variables could be defined in json
    local protocol="both" name="" apiPath="" type="" documentRoot="" innerPort=""
    eval "${values}"
    case "${protocol}" in
        "http")
            generate_lighttpd_config "${file}" "${LIGHTTPD_CONFIG_DIR}" 80
            ;;
        "https")
            generate_lighttpd_config "${file}" "${LIGHTTPD_CONFIG_DIR}" 443
            ;;
        *)
            generate_lighttpd_config "${file}" "${LIGHTTPD_CONFIG_DIR}" 80
            generate_lighttpd_config "${file}" "${LIGHTTPD_CONFIG_DIR}" 443
            ;;
    esac
}

# Check if a file path is provided
if [ $# -eq 0 ]; then
    echo "Usage: $0 <path_to_static_config_files>"
    exit 1
fi
ret=0

# Process each file
for file in "$@"; do
    # We have optional static configs under /etc/lwr/static-config/http/optional, don't process them
    if [[ -d "$file" ]]; then
        echo "Skipping directory: ${file}" >&2
        continue
    fi
    process_static_config "${file}"
    ret=$((ret + $?))
done

exit "${ret}"
