#!/bin/bash
IPMAN_LIB_PATH=$(dirname ${BASH_SOURCE[0]})
source "${IPMAN_LIB_PATH}/config.sh"

compare_values() {
# Compare the JSON objects and output the differences
jq --argjson a "${1}" --argjson b "${2}" -n '
  def diff(a; b):
    if a == b then
      empty
    elif (a | type) == "object" and (b | type) == "object" then
      reduce (a + b | keys_unsorted[]) as $key ({}; 
        if (a[$key] != b[$key]) then 
          . + {($key): diff(a[$key]; b[$key])} 
        else 
          . 
        end)
    else
      b
    end;
  diff($a; $b)
'  | tr -d '\n {}"'
}
# Set and apply interface property
# Arguments:
# 1: config file
# 2: interface name
# 3..: jq set commands (relative to interface config)
# Returns 1 if failed to set property, and prints error message to stdout
function ipman_modify_interface_config() {
    local -r config_file="${1}"
    local -r interface="${2}"
    local jq_commands=()
    for param in "${@:3}"; do
        # .ipv4.dhcp.linklocalFallback=true -> (.interfaces[] | select(.name == "DEFAULT").ipv4.dhcp.linklocalFallback)=true
        jq_commands+=("(.interfaces[] | select(.name == \"$interface\"))${param}")
    done
    local interface_config_before
    interface_config_before="$(${IPMAN_LIB_PATH}/ipman-show ${config_file} ${interface})"
    if [[ $? -ne 0 ]]; then
        return 1
    fi

    ipman_modify_config "${config_file}" "${jq_commands[@]}"
    if [[ $? -ne 0 ]]; then
        return 1
    fi
    local interface_config;
    interface_config="$(${IPMAN_LIB_PATH}/ipman-show ${config_file} ${interface})"
    if [[ $? -ne 0 ]]; then
        return 1
    fi
    change=$(compare_values "${interface_config_before}" "${interface_config}")
    if [[ ${#change} -gt 0 ]]; then
        ipman_emit_config_changed "${interface}" "${change}"
    fi
    # ipman-apply can be called even if nothing was changed, because it will determine what to do (or not to do) according actual status
    ${IPMAN_LIB_PATH}/ipman-apply "${interface}" "${interface_config}"
}

# Set and apply interface property
# Arguments:
# 1: config file
# 2: interface name
# 3: property name
# 4: property value
# Returns 1 if failed to set property, and prints error message to stdout
function ipman_set_interface_property() {

    local -rA IPMAN_CONFIG_BOOL_INTERFACE_PROPERTIES=(
        ["enable"]="enabled"
        ["dhcp-enable"]="ipv4.dhcp.enabled"
        ["dhcp-linklocal-fallback"]="ipv4.dhcp.linklocalFallback"
        ["static-enable"]="ipv4.static.enabled"
        ["linklocal-enable"]="ipv4.linklocal.enabled"
    )

    local config_file=${1}
    local interface=${2}
    local property=${3}
    shift 3

    if [[ -n "${IPMAN_CONFIG_BOOL_INTERFACE_PROPERTIES[${property}]:-}" ]]; then
        if [[ $# -lt 1 ]]; then
            echo "Missing argument for ${property}!"
            return 1
        fi

        local json_value
        if [[ "${1}" == "0" ]]; then
            json_value="false"        
        elif [[ "${1}" == "1" ]]; then
            json_value="true"        
        else
            echo "Invalid argument for ${property}!"
            return 1
        fi
        ipman_modify_interface_config "${config_file}" "${interface}" ".${IPMAN_CONFIG_BOOL_INTERFACE_PROPERTIES[${property}]}=${json_value}"

    elif [[ "${property}" == "static-ip" ]]; then
        if [[ $# -lt 1 ]]; then
            echo "Missing argument for ${property}!"
            return 1
        fi

        ipman_modify_interface_config "${config_file}" "${interface}" ".ipv4.static.ip=\"${1}\""

    elif [[ "${property}" == "static-gateway" ]]; then
        if [[ $# -lt 1 ]]; then
            echo "Missing argument for ${property}!"
            return 1
        fi

        ipman_modify_interface_config "${config_file}" "${interface}" ".ipv4.static.gateway=\"${1}\""

    elif [[ "${property}" == "static" ]]; then
        if [[ $# -lt 2 ]]; then
            echo "Missing argument for ${property}!"
            return 1
        fi

        ipman_modify_interface_config "${config_file}" "${interface}" ".ipv4.static.ip=\"${1}\"" ".ipv4.static.gateway=\"${2}\""

    elif [[ "${property}" == "config" ]]; then
        if [[ $# -eq 0 ]]; then
            echo "Missing config json object!"
            return 1
        fi

        ipman_modify_interface_config "${config_file}" "${interface}" " |={\"name\": \"${interface}\"} + ${1}"

    else
        echo "Unable to set unsupported property: ${property}!"
        return 1
    fi
}

# Modify a property of a network interface.
# Arguments: 
# 1: dynamic configuration file
# 2: interface name
# 3: property name
# 4: property value
# If any error occures, it prints error message to stderr and help to stdout, then terminates the process
function ipman_set() {
    local dynamic_config="${1}"
    shift
    local pos_args=("${@}")

    if [[ ${#pos_args[@]} -lt 2 ]]; then
        echo "Missing argument for: ipman set <interface> <property> <new-value..>"
        return 1
    fi
    local interface="${pos_args[0]}"
    
    ipman_set_interface_property "${dynamic_config}" "${interface}" "${pos_args[@]:1}"
}

ipman_set "${@}"
