#!/bin/bash

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

# prints primary interface name to stdout.
# If any error occures, it prints error message to stderr and help to stdout, then terminates the process
dynamic_config_path="${1}"

config=$(ipman_read_config "${dynamic_config_path}")
if [[ ${?} -ne 0 ]]; then
    >&2 echo "Failed to read config from ${dynamic_config_path}"
    return 1
fi

enabled_interface_names=$(jq -er '.interfaces[] | select(.enabled == true) | .name' <<< "${config}")
if [[ ${?} -ne 0 ]]; then
    >&2 echo "Failed to get interface list"
    return 1
fi

primary_interface=""
highest_prio=$(printf '%u' 0xffffffff) # start from the lowest possible prio (high number means low prio)

for interface in ${enabled_interface_names}; do
    prio=$(netman priority "${interface}")
    if [[ ${?} -ne 0 ]]; then
        >&2 echo "Failed to get priority for interface ${interface}"
        return 1
    fi
    if [[ ${prio} -lt ${highest_prio} ]]; then
        highest_prio=${prio}
        primary_interface="${interface}"
    fi
done

echo "${primary_interface}"
