#!/bin/bash

set -u

LIB_PATH="$(dirname ${BASH_SOURCE[0]})/../lib/lwr/netman/internal"
. ${LIB_PATH}/netman-check-utils

function help() {
    echo "
Usage:
    netman list
    netman show <interface_name>
    netman show <interface_name> linklocal-enabled
    netman linklocal-interface
    netman linux-name <interface_name>
    netman priority <interface_name>
    netman subnet-collision-check
    netman check-config

Commands:
    list
        Lists all interfaces present in the static config.

    show <interface_name>
        Returns the static config for the given network interface in json format.

    show <interface_name> linklocal-enabled
        Returns the state of the link local enabled setting in 'on' or 'off' or 'selectable' format for the specified interface.

    linklocal-interface
        Returns the name of the only one interface, that has link-local IP configuration enabled.

    linux-name <interface_name>
        Returns the linux name of the given interface.

    priority <interface_name>
        Returns the priority of the given interface.

    subnet-collision-check
        Returns subnetCollisionCheck configuration as 'true' or 'false'. Used by lwr-ipman. Default answer is 'true' if the config key is missing.

    check-config
        Checks the static-config.
"
}

function fail() {
    echo -e "${@}"
    help
    exit 1
}

function list() {
    local static_config_path="${1}"
    jq -r '.interfaces[].name' "${static_config_path}"
}

function show() {
    local static_config_path="${1}"
    shift
    local pos_args=("${@}")

    local interface_name=
    local link_local_enable=0

    if [[ ${#pos_args[@]} -gt 0 ]]; then
        interface_name="${pos_args[0]}"
        shift

        # get the remaining last argument, if it is linklocal-enabled
        if [[ ${#pos_args[@]} -eq 2 ]]; then
            if [[ ${pos_args[1]} == "linklocal-enabled" ]]; then
                link_local_enable=1
            else
                fail "Unknown argument: ${pos_args[1]}"
            fi
        fi
    else
        fail "Missing interface name"
    fi

    local interface_config
    interface_config=$(jq -e --arg interface "${interface_name}" '.interfaces[] | select(.name == $interface)' ${static_config_path})
    exit_code=$?
    if [ ${exit_code} -ne 0 ]; then
        echo "Given interface [${interface_name}] was not found in static config file [${static_config_path}]!"
        exit ${exit_code}
    fi

    if [[ ${link_local_enable} -eq 0 ]]; then
       echo "${interface_config}" | jq .
    else
       linklocal_enable_value=$(jq -r --arg interface "${interface_name}" '.interfaces[] | select(.name == $interface) | if has("linklocalEnable") then .linklocalEnable else "off" end' "${static_config_path}")
       echo "${linklocal_enable_value}"
    fi
}

function get_linklocal_enabled_interface() {
    local static_config_path="${1}"
    local interface_name
    local linklocal_enable
    read interface_name linklocal_enable <<< $(jq -r '.interfaces[] | select(.linklocalEnable == "on" or .linklocalEnable == "selectable") | "\(.name) \(.linklocalEnable)"' "${static_config_path}")
    if [[ ! -z "${interface_name}" ]]; then
        echo "${interface_name}" "${linklocal_enable}"
    fi
}

function get_linux_name() {
    local static_config_path="${1}"
    shift
    local pos_args=("${@}")

    local interface_name
    if [[ ${#pos_args[@]} -gt 0 ]]; then
        interface_name="${pos_args[0]}"
    else
        fail "Missing interface name"
    fi

    read dev vlanid <<< $(jq -r --arg name "$interface_name" '.interfaces[] | select(.name == $name) | "\(.dev) \(.vlanid // "")"' $static_config_path)

    local linux_name="${dev}"
    if [ ! -z ${vlanid} ]; then
        linux_name="${linux_name}.${vlanid}"
    fi

    echo "${linux_name}"
}

function get_priority() {
    local static_config_path="${1}"
    shift
    local pos_args=("${@}")

    local interface_name
    if [[ ${#pos_args[@]} -eq 0 ]]; then
        fail "Missing interface name"
    fi

    interface_name="${pos_args[0]}"

    jq -er --arg name "$interface_name" '.interfaces[] | select(.name == $name) | .priority' $static_config_path
}

function get_subnet_collision_check() {
    local static_config_path="${1}"
    jq -r 'if (.subnetCollisionCheck | type) == "boolean" then .subnetCollisionCheck else true end' $static_config_path
}

function check_config() {
    local static_config_file="${1}"

    checkStaticConfigExists "${static_config_file}"

    checkJsonSchema "${static_config_file}"
    checkInterfaceNamesAreUnique "${static_config_file}"
    checkSingleLinklocalEnableOnOrSelectablePresent "${static_config_file}"
    checkVlanidsAreUniquePerDevice "${static_config_file}"
    checkPriorityIsGloballyUnique "${static_config_file}"

    exit 0
}

function main() {
    local static_config="/etc/lwr/static-config/lwr-netman/interfaces.json"
    subcommand="${1:-}"
    shift

    # get out static config file if added (mainly for test purposes), and store the other arguments
    positional_args=()
    while [[ $# -gt 0 ]]; do
        case ${1} in
            -c|--config-file)
                static_config=${2}
                if [ ! -f "${static_config}" ]; then
                    fail "Given static-config: ${static_config} not exists!"
                fi
                shift
                ;;
                --*|-*)
                    fail "Unknown option: ${1}"
                    ;;
                *)
                    if [[ -n "${1}" ]]; then
                        positional_args+=("${1}")
                    fi
        esac
        shift
    done

    case $subcommand in
        list)
            list "${static_config}"
            ;;
        show)
            show "${static_config}" "${positional_args[@]}"
            ;;
        linklocal-interface)
            get_linklocal_enabled_interface "${static_config}"
            ;;
        linux-name)
            get_linux_name "${static_config}" "${positional_args[@]}"
            ;;
        priority)
            get_priority "${static_config}" "${positional_args[@]}"
            ;;
        subnet-collision-check)
            get_subnet_collision_check "${static_config}"
            ;;
        check-config)
            check_config "${static_config}"
            ;;
        -h|--help)
            help
            ;;
        *)
            fail "netman got unknown subcommand: $subcommand"
            ;;
    esac
}

main "$@"