#!/bin/sh

. /lib/functions.sh

function logger() {
    command logger -t lh-migration "$@"
    echo "$@" >> /tmp/lh-migration.log
}

function lh_filter() {
    if [ -z "$LINUX_HOST_CONFIG" ]; then
        LINUX_HOST_CONFIG="$(chunk -F - extract_config | gunzip | xml2json)"
        [ -z "$LINUX_HOST_CONFIG" ] && {
            logger "Failed reading LH configuration";
            exit 1;
        }
    fi
    echo "`jsonfilter -s "$LINUX_HOST_CONFIG" -e "$1"`"
}

function lh_config_version() {
    echo "$(lh_filter $.SystemConfig.Config.Version)"
}

function lh_config_deviceType() {
    echo "$(lh_filter $.SystemConfig.Services.System.Baptization.DeviceType)"
}

function lh_config_hostname() {
    echo "$(lh_filter $.SystemConfig.Services.System.Baptization.Hostname)"
}

function lh_iterate_array() {
    local NameSingular="$1"
    local NamePlural="$2"
    local Callback="$3"
    local Context="$4"

    local Type
    if json_get_type Type "$NameSingular" && [ "$Type" = object ]; then
        json_select "$NameSingular"
        $($Callback $Idx "$Context")
        json_select ..
    else
        if json_get_type Type "$NamePlural" && [ "$Type" = array ]; then
            json_select "$NamePlural"
            local Idx=1
            while json_get_type Type $Idx && [ "$Type" = object ]; do
                json_select $Idx
                $($Callback $Idx "$Context")
                json_select ..
                Idx=$((Idx+1))
            done
            json_select ..
        fi
    fi
}

