#!/bin/bash

set -u

IPMAN_LIB_PATH="$(dirname ${BASH_SOURCE[0]})/../lib/lwr/ipman"
source "${IPMAN_LIB_PATH}/ip-functions.sh"
source "${IPMAN_LIB_PATH}/events.sh"

set_default_gateway() {
    local interface_name="${1}"
    local interface_config="${2}"
    local priority
    priority=$(netman priority "${interface_name}")
    if [[ $? -ne 0 ]]; then
        logger -s user.error "Failed to read priority for interface '${interface_name}': ${priority}"
        return 1
    fi

    local gateway
    gateway=$(jq -re ".ipv4.static.gateway" <<< "${interface_config}")
    if [[ $? -ne 0 ]]; then
        logger -s user.error "Failed to read static gateway for ${interface_name}"
	return 1
    fi

    logger user.debug "Add default gateway ${gateway} to ${interface_name}"
    ipman_add_default_route "${interface_name}" "${gateway}" "static" "${priority}" || true
}

interface_name=${1}

interface_config="$(ipman show "${interface_name}")"
if [[ $? -ne 0 ]]; then
    logger -s user.error "Could not read config for ${interface_name}! Reason: '${interface_config}'"
    exit 1
fi

IP=$(jq -re ".ipv4.static.ip" <<< "${interface_config}")
if [[ $? -ne 0 ]]; then
    logger -s user.error "Failed to read static ip for ${interface_name}"
    exit 1
fi

# If the configured IP address overlaps with e.g. the dynamiccally obbtained address, but DHCP is disabled at the same
# moment, then we cannot configure immediately the static IP. The retry count and the wait interval is based on the bug
# description below, and further adjustments could be necessary.
#
# On LLVD, one retry without any sleep makes the tests passed. On the taurus reffered by the issue below suggests that
# it takes ~2s to revoke the conflicting ip address.
#
# See: https://jira.in.lightware.com/browse/EMB3-1820 (Static network setting disables both with overlapping dynamic
# address)
for retry_count in {2..0}; do
    if validate_address_overlapping "${IP}"; then
        logger user.debug "Add static ip address ${IP} to ${interface_name} (remaining ${retry_count} attempt)"
        ipman_add_labeled_address "${interface_name}" "${IP}" "static"
        set_default_gateway "${interface_name}" "${interface_config}"
        ipman_emit_status_changed "${interface_name}" "static" "valid"
        exit 0
    fi

    logger user.notice "Failed to set IP address: ${IP} on ${interface_name} (remaining ${retry_count} attempt)"
    if [[ ${retry_count} -ne 0 ]]; then
        sleep 1
    fi
done

logger -s user.error "Failed to set static ip for ${interface_name}, desired IP: ${IP}"
exit 1
