#!/bin/bash

set -eu -o pipefail

export uid_mac_dir="/uid/mac_addresses"
export uid_addon_dir="/uid/addon_boards"
uid_secret_dir="/uid/secrets"
uid_features_dir="/uid/features"
partnumbers_file_path="/etc/lwr/static-config/lwr-system-info/partnumbers.xml"
version_file_path="/version.xml"
components_file_path="/distro.xml"
hook_dir="/etc/lwr/static-config/lwr-system-info/hooks"

system_info_uid_mac_exists() {
    local mac_name="${1:?-Missing mac name}"

    local mac_path="${uid_mac_dir}/${mac_name}"
    [ -f "${mac_path}" ]
}

#
# Parameters:
#   <mac_name> Name of MAC-address
# Precondition: <mac_name> must exist in uid (system_info_uid_mac_exists <mac_name> must return 0)
# Returns the corresponding MAC-address for <mac_name>
#
system_info_uid_mac() {
    local mac_name="${1:?-Missing mac name}"

    local mac_path="${uid_mac_dir}/${mac_name}"
    if system_info_uid_mac_exists "${mac_name}"; then
        echo "$(cat "${mac_path}")"
    else
        echo "No such MAC in uid: ${mac_name}" >&2
        exit 2
    fi
}

system_info_uid_mac_names() {
    find ${uid_mac_dir} -mindepth 1 -maxdepth 1 -type f -exec basename {} \;
}

export -f system_info_uid_mac
export -f system_info_uid_mac_exists
export -f system_info_uid_mac_names

invoke_hook() {
    local hook_name="${1}"
    if [ -f "${hook_dir}/${hook_name}" ]; then
        "${hook_dir}/${hook_name}"
        ec=${?}
        # Fail fast: system-info should be stable, so if the hook returns an error the system may not work properly
        if [[ $ec -ne 0 ]] ; then
            exit ${ec}
        fi
    fi
}

get_package_version() {
    major=$(xmllint --xpath 'number(/package/packageVersion/version/major)' ${version_file_path})
    minor=$(xmllint --xpath 'number(/package/packageVersion/version/minor)' ${version_file_path})
    hotfix=$(xmllint --xpath 'number(/package/packageVersion/version/hotfix)' ${version_file_path})
    rc=$(xmllint --xpath 'number(/package/packageVersion/version/rc)' ${version_file_path})

    echo "v${major}.${minor}.${hotfix}b${rc}"
}

get_package_reference() {
    xmllint --xpath 'string(/package/packageVersion/referenceName)' ${version_file_path}
}

get_package_git_hash() {
    xmllint --xpath 'string(/package/packageVersion/versionControlSystem/value)' ${version_file_path}
}

get_package_buildjob() {
    jobName=$(xmllint --xpath 'string(/package/packageVersion/buildJob/jobName)' ${version_file_path})
    jobNumber=$(xmllint --xpath 'number(/package/packageVersion/buildJob/jobNumber)' ${version_file_path})

    echo "${jobName} #${jobNumber}"
}

get_package_date() {
    year=$(xmllint --xpath 'number(/package/packageVersion/date/year)' ${version_file_path})
    month=$(xmllint --xpath 'number(/package/packageVersion/date/month)' ${version_file_path})
    day=$(xmllint --xpath 'number(/package/packageVersion/date/day)' ${version_file_path})
    hour=$(xmllint --xpath 'number(/package/packageVersion/date/hour)' ${version_file_path})
    minute=$(xmllint --xpath 'number(/package/packageVersion/date/minute)' ${version_file_path})

    echo "${day}/${month}/${year} ${hour}:${minute}"
}

get_product_name() {
    local part_number=$(get_uid_attribute PartNumber)
    echo $(xmllint --xpath "string(variants/variant[partnumber='${part_number}']/productname)" "${partnumbers_file_path}")
}

get_usb_pid() {
    local part_number=$(get_uid_attribute PartNumber)
    echo $(xmllint --xpath "string(variants/variant[partnumber='${part_number}']/usbpid)" "${partnumbers_file_path}")
}

get_uid_attribute() {
    local attribute="${1}"
    cat "/uid/${attribute}"
}

get_component_attribute() {
    local component_name=${1}
    local attribute=${2}

    value=$(xmllint --xpath "string(packages/package[name='${component_name}']/${attribute})" ${components_file_path})
    if [[ -z "${value}" ]]; then
        echo "Cannot find '${attribute}' in component named '${component_name}'" >&2
        echo "N/A"
        return 2
    fi

    echo ${value}
}

get_distro_xml() {
    cat "${components_file_path}"
}

list_mac_names() {
    local mac_names
    mac_names=$(system_info_uid_mac_names)
    mac_names+="\n$(invoke_hook "mac" | awk '{print $1}')"

    # The following awk command removes duplicated entries without sorting them. NF is for removing empty lines
    echo -e "${mac_names}" | awk 'NF && !x[$0]++'
}

list_addon_names() {
    if [[ ! -d ${uid_addon_dir} ]]; then
        return 0;
    fi
    find ${uid_addon_dir} -mindepth 1 -maxdepth 1 -type d -exec basename {} \;
}

list_secret_names() {
    if [[ ! -d ${uid_secret_dir} ]]; then
        return 0;
    fi
    find ${uid_secret_dir} -mindepth 1 -maxdepth 1 -type f -exec basename {} \;
}

list_componens() {
    xmllint --xpath "/packages/package[*]/name/text()" ${components_file_path}
}

get_component() {
    local component_name=${1}
    set +e
    version=$(get_component_attribute "${component_name}" version)
    date=$(get_component_attribute "${component_name}" date)
    site=$(get_component_attribute "${component_name}" site)
    set -e
    jq -n --arg version "${version}" --arg date "${date}" --arg site "${site}" '{"version": $version, "date": $date, "site": $site}'
}

get_components() {
    #FIXME: it's too slow. maybe don't read xml million times...
    local delimiter="{"
    list_componens | while read line ; do 
        echo "${delimiter}"
        delimiter=","
        echo "\"${line}\": $(get_component ${line})" ; 
    done
    echo "}"
}

get_fallback_default_password() {
    #avoid always regenerating salt and return with different hash for fallback default password
    local lib_dir="/usr/lib/lwr/lwr-system-info-getter"
    local fallback_password_file="${lib_dir}/fallbackPasswd"
    if [[ ! -f "${fallback_password_file}" ]]; then
        mkdir -p ${lib_dir}
        
        #head sends signal to base64 which will be caught by pipefail and causes script to exit
        set +o pipefail
        salt=$(base64 < /dev/urandom | head -c 22)
        set -o pipefail
        
        mkpasswd -m sha512 "Lightware10g" "${salt}" > "${fallback_password_file}"
    fi

    cat ${fallback_password_file}
}

# Precondition mac name must exist, either in uid or mac hook
get_mac_value() {
    local mac_name=${1}
    if system_info_uid_mac_exists "${mac_name}"; then
        system_info_uid_mac "${mac_name}"
    else
        # awk command explanation:
        # it checks if the element in the first column matches exactly to 'mac_name' then returns the second column
        invoke_hook "mac" | awk -v v="^${mac_name}$" '$1 ~ v {print $2}'
    fi
}

check_system_integrity() {
    local error_code=0
    if [[ ! -f ${version_file_path} ]]; then echo "[ERROR] ${version_file_path} does not exists!"; error_code=1; fi
    if [[ ! -f ${components_file_path} ]]; then echo "[ERROR] ${components_file_path} does not exists!"; error_code=1; fi
    if [[ ! -f ${partnumbers_file_path} ]]; then echo "[ERROR] ${partnumbers_file_path} does not exists!"; error_code=1; fi
    if [[ ! -d "/uid" ]]; then echo "[ERROR] /uid directory does not exist!"; error_code=1; fi

    if [[ ${error_code} -ne 0 ]]; then
        echo -e "\nSome system functions may not work correctly"
    fi

    return ${error_code}
}

list_features_names() {
    if [[ ! -d ${uid_features_dir} ]]; then
        return 0;
    fi
    find ${uid_features_dir} -mindepth 1 -maxdepth 1 -type d -exec basename {} \;  
}

show_usage() {
    echo "get-system-info PartNumber|SerialNumber|HardwareVersion|ProductName|UsbPid|EolTestId|macNames|addonNames|featureNames|secretNames"
    echo "get-system-info mac $(list_mac_names | paste -s -d '|' -)"
    echo "get-system-info addon $(list_addon_names | paste -s -d '|' -) PartNumber|SerialNumber|HardwareVersion"
    echo "get-system-info PackageVersion|PackageReference|PackageBuildJob|PackageDate|PackageGitHash"
    echo "get-system-info components [xml|json]"
    echo "get-system-info component <component-name> [version|name|site]"
    echo "get-system-info feature <feature-name> PartNumber|SerialNumber|ProductName"
    echo "get-system-info secret $(list_secret_names| paste -s -d '|' -)"
    echo "  This command implements the system-info-getter interface:"
    echo "    https://git.in.lightware.com/experimental-sandbox/system_info/system-info-getter"
}

case ${1:-} in
    PartNumber|SerialNumber|HardwareVersion)
        get_uid_attribute "${1}"
        ;;
    EolTestId)
        get_uid_attribute "eoltest/EolTestId"
        ;;
    ProductName)
        get_product_name
        ;;
    UsbPid)
        get_usb_pid
        ;;
    PackageVersion)
        get_package_version
        ;;
    PackageReference)
        get_package_reference
        ;;
    PackageBuildJob)
        get_package_buildjob
        ;;
    PackageDate)
        get_package_date
        ;;
    PackageGitHash)  
        get_package_git_hash
        ;;
    macNames)
        list_mac_names
        ;;
    addonNames)
        list_addon_names
        ;;
    featureNames)
        list_features_names
        ;;
    secretNames)
        list_secret_names
        ;;
    feature)
        feature_name=${2:?"Missing feature name"}
        feature_attribute=${3:?"Missing feature attribute"}
        if [[ ! -d "${uid_features_dir}/${feature_name}" ]]; then
            echo "Unknown feature name: ${feature_name}" >&2
            exit 2
        fi
        if ! echo -e "PartNumber\nSerialNumber\nProductName" | grep -qw "${feature_attribute}"; then
            echo "Unknown feature attribute: ${feature_attribute}" >&2
            echo "Select one from: PartNumber|SerialNumber|ProductName" >&2
            exit 2
        fi
        if [[ ! -f "${uid_features_dir}/${feature_name}/${feature_attribute}" ]]; then
            echo "Missing feature attribute: ${feature_attribute}" >&2
            exit 1
        fi
        cat "${uid_features_dir}/${feature_name}/${feature_attribute}"
        ;;
    mac)
        mac_name=${2:?"Missing mac name"}
        mac_names=$(list_mac_names)
        if ! grep -q "${mac_name}" <<< "${mac_names}"; then
            echo "Unknown mac name: ${mac_name}" >&2
            echo "Select one from: $(list_mac_names)" >&2
            show_usage
            exit 2
        fi
        get_mac_value "${mac_name}"
        ;;
    addon)
        addon_name=${2:?"Missing addon name"}
        attribute=${3:?"Missing addon attribute"}
        if [[ ! -d "${uid_addon_dir}/${addon_name}" ]]; then
            echo "Unknown addon name: ${addon_name}" >&2
            echo "Select one from: $(list_addon_names)" >&2
            show_usage
            exit 2
        fi
        get_uid_attribute "addon_boards/${addon_name}/${attribute}"
        ;;
    components)
        if [ -z ${2+x} ]; then
            list_componens
        else
            if [[ "${2}" = "xml" ]]; then
                get_distro_xml
            elif [[ "${2}" = "json" ]]; then
                get_components
            else
                echo "Unknown component list type: ${2}" >&2
                echo "Select one from: xml|json" >&2
                show_usage
                exit 2
            fi
        fi
        ;;
    component)
        component_name=${2:?"Missing component name"}
        if [ -z ${3+x} ]; then
            get_component ${component_name}
        else
            if [[ "${3}" = "version" ]]; then
                get_component_attribute ${component_name} "version"
            elif [[ "${3}" = "site" ]]; then
                get_component_attribute ${component_name} "site"
            elif [[ "${3}" = "date" ]]; then
                get_component_attribute ${component_name} "date"
            else
                echo "Unknown component attribute: ${3}" >&2
                echo "Select one from: version|site|date" >&2
                show_usage
                exit 2
            fi
        fi
        ;;
    secret)
        secret_name=${2:?"Missing secret name"}
        if [[ ! -f "${uid_secret_dir}/${secret_name}" ]]; then
             if [[ ${secret_name} != "DefaultPasswordHash" ]]; then
                echo "Unknown secret name: ${secret_name}" >&2
                echo "Select one from: $(list_secret_names)" >&2
                show_usage
                exit 2
            fi
            
            # Concurrent calls could result multiple redundant generation of the fallbackPasswd file. This also can
            # return empty output which may result empty password field in the shadow file
            #
            # See related issue: https://jira.in.lightware.com/browse/EMB3-1817
            # Affected component: setman default script in password-api-plugin
            fallback_pwd_path=/tmp/fallbackPasswd.lock
            (
                flock 200
                get_fallback_default_password
            ) 200>"${fallback_pwd_path}"
        else
            get_uid_attribute "secrets/${secret_name}"
        fi
        ;;
    check)
        check_system_integrity
        ;;
    *)
        echo "Unknown subcommand: ${1:-}" >&2
        show_usage
        exit 2
esac
