#!/bin/bash

SCHEMA_VALIDATOR_JSON="${SCHEMA_VALIDATOR_JSON:-"/usr/lib/lwr/netman/schema-validator.js"}"

function checkStaticConfigExists() {
    local static_config_file=${1}
    if [ ! -e "${static_config_file}" ]; then
        echo "Static config not found! [${static_config_file}]"
        exit 1
    fi
}

checkJsonSchema() {
    local path=${1}
    local static_config_data=$(cat "${path}")
    export static_config_data
    export SCHEMA_VALIDATOR_JSON
    # Node.js code block
node << 'EOF'
schemaValidator = require(process.env.SCHEMA_VALIDATOR_JSON);
fs = require('fs');

try{
    const data = JSON.parse(process.env.static_config_data.toString());
    const valid = schemaValidator(data);
    if (valid) {
        process.exit(0);
    } else {
        console.log('Invalid:', schemaValidator.errors);
        process.exit(1);
    }
} catch(e) {
    console.log('Error during schema validation:', e);
    process.exit(1);
}
EOF
   if [ $? -ne 0 ]; then
       echo "Static config schema validation failed!"
       exit 1
   fi
}

function checkInterfaceNamesAreUnique() {
    local static_config_file=${1}
    if [[ $(jq -r '.interfaces[].name' ${static_config_file} | sort | uniq -d) ]]; then
        echo "Duplicated interface 'name'-s found!"
        exit 1
    fi
}

function checkSingleLinklocalEnableOnOrSelectablePresent() {
    local static_config_file=${1}
    local count_enabled=$(jq -r '[.interfaces[].linklocalEnable | select(. == "on" or . == "selectable")] | length' "${static_config_file}")

    if [ "${count_enabled}" -gt 1 ]; then
        echo "Error: More than one 'linklocalEnable' with value 'on' or 'selectable' found."
        exit 1
    fi
}

function checkVlanidsAreUniquePerDevice() {
    local static_config_file=${1}
    if [[ $(jq -r '.interfaces[] | "\(.dev)#\(.vlanid // "N/A")"' ${static_config_file} | sort | uniq -d) ]]; then
        echo "Duplicated vlanid for a single dev found!"
        exit 1
    fi
}

function checkPriorityIsGloballyUnique() {
    local static_config_file=${1}
    if [[ $(jq -r '.interfaces[].priority // empty' ${static_config_file} | sort | uniq -d) ]]; then
        echo "Duplicated 'priority'-s found!"
        exit 1
    fi
}