#!/bin/bash
IPMAN_LIB_PATH=$(dirname ${BASH_SOURCE[0]})
source "${IPMAN_LIB_PATH}/ip-functions.sh"
source "${IPMAN_LIB_PATH}/events.sh"
source "${IPMAN_LIB_PATH}/config.sh"
source "${IPMAN_LIB_PATH}/ipman.env"

# This method supposes that the service is running, but there might happen something that needs to be applied
# Return codes:
#   0: reload needed
#   1: no need to reload
#   else: error happened
#
function ipman_should_be_reloaded() {
    local interface="${1}"
    local interface_config="${2}"
    local net_type="${3}"

    case "${net_type}" in
        static)
            local desired_ip
            local desired_gw
            local current_ip
            read -r desired_ip desired_gw < <(jq -r '"\(.ipv4.static.ip) \(.ipv4.static.gateway)"' <<< "${interface_config}")
            current_ip=$(ipman_get_ip_address_from_labeled_interface_name "${interface}" "${net_type}")
            if [[ $? -ne 0 ]]; then
                echo "Error during get addresses for ${interface} (${net_type})"
                return 2;
            fi

            if [[ "${current_ip}" != "${desired_ip}" ]]; then
                echo "Ip address is different: (current: ${current_ip}, desired: ${desired_ip})"
                return 0;
            fi

            local current_gw
            current_gw=$(ipman_get_default_route_gateway "${interface}" "${net_type}")
            if [[ $? -ne 0 ]]; then
                echo "Error during get gateway for ${interface} (${net_type})"
                return 2;
            fi

            if [[ "${current_gw}" != "${desired_gw}" ]]; then
                echo "Gateway is different: (current: ${current_gw}, desired: ${desired_gw})"
                return 0;
            fi

            return 1

            ;;
        dhcp)
            if [[ "$(systemctl is-active network-linklocal@${interface}.service)" == "active" ]]; then
                if [[ "$(jq -r ".ipv4.dhcp.linklocalFallback" <<< ${interface_config})" == "false" ]]; then
                    if [[ "$(jq -r ".ipv4.linklocal.enabled" <<< ${interface_config})" == "false" ]]; then
                        return 0;
                    fi
                fi
            fi

            return 1;
            ;;
        linklocal)
            return 1;
            ;;
        *)
            echo "Fatal error! Invalid net type: ${net_type}"
            caller
            return 2
    esac
}

function ipman_interface_up() {
    local operstate
    operstate=$(ip -j a show "${interface}" | jq -re '.[].operstate')
    if [[ $? -ne 0 ]]; then
        echo "Could not apply '${interface}' config: Failed to read interface operation state! '${operstate}'"
        return 1
    fi

    if [[ "${operstate}" != "UP" ]]; then
        echo "Set interface '${interface}' UP"
        if ! ip link set "${interface}" up ; then
            echo "Could not apply '${interface}' config: Failed to set interface up!"
            return 1
        fi
        ipman_emit_status_changed "${interface}" "" "UP"
    fi

    return 0
}

function ipman_interface_down() {
    local operstate
    operstate=$(ip -j a show "${interface}" | jq -re '.[].operstate')
    if [[ $? -ne 0 ]]; then
        echo "Could not apply '${interface}' config: Failed to read interface operation state! '${operstate}'"
        return 1
    fi

    if [[ "${operstate}" != "DOWN" ]]; then
        echo "Set interface '${interface}' DOWN"
        if ! ip link set "${interface}" down; then
            echo "Could not apply '${interface}' config: Failed to set interface down!"
            return 1
        fi
        ipman_emit_status_changed "${interface}" "" "DOWN"
    fi

    return 0
}

function ipman_apply_settings_for() {
    local interface="${1}"
    local interface_config="${2}"
    local net_type="${3}"

    local service_enabled
    local service_status
    service_enabled=$(jq -r ".ipv4.${net_type}.enabled" <<< "${interface_config}")
    service_status=$(systemctl is-active "network-${net_type}@${interface}.service")

    # Handle enabled service
    if [[ "${service_enabled}" == "true" ]]; then
        if [[ "${service_status}" == "active" ]]; then
            ipman_should_be_reloaded "${interface}" "${interface_config}" "${net_type}"
            if [[ $? -eq 0 ]]; then
                logger -t "lwr-ipman-apply" "Reloading network-${net_type} for ${interface}"
                systemctl reload-or-restart "network-${net_type}@${interface}.service"
            fi
            return 0
        fi

        logger -t "lwr-ipman-apply" "Start ${interface}/${net_type}"
        systemctl start "network-${net_type}@${interface}.service"
        if [[ $? -ne 0 ]]; then
            echo "Unable to start network-${net_type} for ${interface}"
            systemctl status "network-${net_type}@${interface}.service"
            return 1
        fi
        local service_status
        service_status=$(systemctl show -p SubState --no-pager --value "network-${net_type}@${interface}.service")
        if [[  "${service_status}" == "running" ]]; then
            ipman_emit_status_changed "${interface}" "${net_type}" "pending"
        fi
        return 0
    fi

    # Handle disabled service
    [[ "${net_type}" == "linklocal" ]] && [[ $(jq -r ".ipv4.dhcp.linklocalFallback" <<< "${interface_config}") == "true" ]]

    local is_link_local_fallback=$?
    # if it's a fallback linklocal, then do not stop it
    if [[ "${service_status}" == "active" && "${is_link_local_fallback}" -ne 0 ]]; then
        logger -t "lwr-ipman-apply" "Stop ${interface}/${net_type}"
        # No need to emit status change, because every systemd has ExecStop, and it should emit change
        systemctl stop "network-${net_type}@${interface}.service"
        return 0
    fi
}

# quite an ugly way for allowing apply_interface config to be mocked
if ! declare -F ipman_apply_interface_config > /dev/null; then
    ipman_apply_interface_config() {
        local interface="${1}"
        local interface_config="${2}"
        local interface_enabled
        interface_enabled=$(jq -r ".enabled" <<< "${interface_config}")
        if [[ $? != 0 ]]; then
            logger -p "user.error" -t "lwr-ipman-apply" "Failed to get ${interface} enabled configuration value."
            return 1
        fi

        if [[ "${interface_enabled}" == "true" ]]; then # Handle enabled interface
            if ! ipman_interface_up; then
                return 1
            fi

            ipman_apply_settings_for "${interface}" "${interface_config}" static &
            ipman_apply_settings_for "${interface}" "${interface_config}" linklocal &
            ipman_apply_settings_for "${interface}" "${interface_config}" dhcp &

        else # Handle disable interface
            systemctl stop "network-static@${interface}.service"
            systemctl stop "network-linklocal@${interface}.service"
            systemctl stop "network-dhcp@${interface}.service"

            if ! ipman_interface_down; then
                return 1
            fi
        fi
    }
fi

ipman_apply_config() {
    local config=${1:-${IPMAN_CONFIG_PATH}}

    local config_data
    config_data=$(ipman_read_config "${config}")
    if [[ $? -ne 0 ]]; then
        echo "Could not read ${config}!"
        return 1
    fi

    local interface_names;
    interface_names=$(${IPMAN_LIB_PATH}/ipman-list-interfaces "${config_data}")

    for interface in ${interface_names}; do
        local interface_config;
        interface_config="$(${IPMAN_LIB_PATH}/ipman-show ${config} ${interface})"
        if [[ $? -ne 0 ]]; then
            logger -t "lwr-ipman-apply" "Could not get interface config for ${interface}"
            continue #best effort: do not return
        fi

        ipman_apply_interface_config "${interface}" "${interface_config}"
        if [[ $? -ne 0 ]]; then
            logger -t "lwr-ipman-apply" "Could not apply initial config for ${interface}"
            continue #best effort: do not return
        fi
    done
}

if [[ $# -lt 2 ]]; then
    ipman_apply_config "${@}"
else
    ipman_apply_interface_config "${@}"
fi
