#!/bin/bash

set -u

source "/usr/lib/lwr/setman/packages/lwr-ipman/custom/paths.sh"

function generate_new_config_from_default_config() {
    local interface_to_modify="${1}"
    local dhcp_enabled="${2}"
    local linklocal_fallback="${3}"
    local static_enabled="${4}"
    local static_ip="${5}"
    local static_gateway="${6}"

    jq -e --arg interface "${interface_to_modify}" \
        --argjson dhcp_enabled "${dhcp_enabled}" --argjson linklocal_fallback "${linklocal_fallback}" --argjson static_enabled "${static_enabled}" \
        --arg staticIp "${static_ip}" --arg staticGateway "${static_gateway}" '
        (.interfaces[] | select(.name == $interface).ipv4.dhcp.enabled)=$dhcp_enabled |
        (.interfaces[] | select(.name == $interface).ipv4.dhcp.linklocalFallback)=$linklocal_fallback |
        (.interfaces[] | select(.name == $interface).ipv4.static.enabled)=$static_enabled |
        (.interfaces[] | select(.name == $interface).ipv4.static.ip)=$staticIp |
        (.interfaces[] | select(.name == $interface).ipv4.static.gateway)=$staticGateway |
        if $linklocal_fallback == true then
            (.interfaces[] | select(.name == $interface).ipv4.linklocal.enabled)=false
        else
            .
        end
    ' "${ROOTFS_PATH}${IPMAN_CONFIG_PATH}"
}

function get_interface_with_linklocal_enabled() {

    read -r linklocal_interface linklocal_enable_static_config <<< $(netman linklocal-interface)
    if [ -n "${linklocal_interface}" ]; then
        echo "${linklocal_interface}"
        return 0
    fi

    return 1
}

function get_values_from_old_config() {
    local old_config="${1}"
    local linklocal_enabled="${2}"

    local dhcp=$(jq -r '.dhcp' "${old_config}") # '.dhcp // <default_value>' would return default_value when dhcp is false
    local static_ip=$(jq -r '.staticIp // "192.168.0.100"' "${old_config}")
    local static_netmask=$(jq -r '.staticNetmask // "255.255.255.0"' "${old_config}")
    local static_gateway=$(jq -r '.staticGateway // "192.168.0.1"' "${old_config}")

    prefix=$(ipcalc --no-decorate -p 0.0.0.0 ${static_netmask})
    if [ ${?} -ne 0 ]; then
        setman-log error "Could not calculate prefix from netmask: ${static_netmask}"
        return 1
    fi

    #get enable values according to dhcp setting
    local dhcp_enabled="false"
    local linklocal_fallback="false"
    local static_enabled="false"

    if [[ "${dhcp}" == "true" ]]; then
        dhcp_enabled="true"
        if [[ ${linklocal_enabled} == "selectable" ]]; then #off->there cant be any linklocal address, on->simple linklocal already enabled, selectable->switch to linklocalFallback
            linklocal_fallback="true"
        fi
    else
        static_enabled="true"
    fi

    echo "${dhcp_enabled}" "${linklocal_fallback}" "${static_enabled}" "${static_ip}/${prefix}" "${static_gateway}"
}

function convert_old_formatted_backup() {
    old_dynamic_config="/tmp/old-dynamic-config.json"
    setman-restore "ipSettings" settings.json > "${old_dynamic_config}"

    interface_to_modify=$(get_interface_with_linklocal_enabled)
    if [ $? -ne 0 ]; then
        setman-log error "Could not get interface with linklocal enabled, fall back to default"
        return 1
    fi

    linklocal_enabled=$(netman show ${interface_to_modify} linklocal-enabled)

    read dhcp_enabled linklocal_fallback static_enabled static_ip static_gateway < <(get_values_from_old_config "${old_dynamic_config}" "${linklocal_enabled}")
    ret_code=${?}
    rm "${old_dynamic_config}"

    if [ ${ret_code} -ne 0 ]; then
        setman-log error "Could not get values from old-config, fall back to default"
        return 1
    fi



    generate_new_config_from_default_config "${interface_to_modify}" "${dhcp_enabled}" "${linklocal_fallback}" "${static_enabled}" "${static_ip}" "${static_gateway}" > "${IPMAN_CONFIG_PATH}"

}

version=$(setman-restore "ipSettings" version.txt)
if [ $? -ne 0 ]; then
    version=1 #If no version assume version is 1 (because we forgot to write version in first implementation)
fi

if [ ${version} -eq 2 ]; then #new formatted config
    setman-restore "ipSettings" settings.json > "${IPMAN_CONFIG_PATH}"
    exit 0;
fi

setman-log warning "Old config format found, convert to new format!"
convert_old_formatted_backup