#!/bin/bash
#  config-scripts/src/share/sys/cd11mux_link.sh
#
#  Copyright: ©2009–2010, Güralp Systems Ltd.
#  Author: Laurence Withers <lwithers@guralp.com>
#  License: GPLv3
#
#   cd11mux configuration link functions
#     These functions simplify configuration of modules which are linked
#     through the data-mux-cd11 multiplexor. Rather than have the user specify
#     the full path to the IPC socket, an iselect is used to allow the user to
#     select the multiplexor from a list of modules. This list employs the
#     user's own description, to make the selection more user-friendly.



# gcs_cd11mux_iselect()
#  This function prints the choices of multiplexor module (data-mux-cd11) in a manner suitable for
#  an iselect, along with choosing a suitable default value for the mux_path variable.
#   $1 -> current setting of "mux_path"
#   $2 -> "source" or "sink"
gcs_cd11mux_iselect() {
    local i default module cfg socket desc

    current_socket="$1"
    source_or_sink="$2"

    i=0
    for cfg in "${CONFIGDIR}/data-mux-cd11/"*.local
    do
        # pull out the socket path, skipping the file if one isn't present
        socket="$(gcs_get_varcf "${source_or_sink}_socket_path" "${cfg}")"
        [ -z "${socket}" ] && continue

        # get the user-friendly instance name
        desc="$(gcs_get_varcf "application_description" "${cfg}")"
        [ -z "${desc}" ] && desc="${socket}"

        # choose a default
        module="$(basename "${cfg}" ".local")"
        [ -z "${default}" ] && default="${module}"
        [ "${module}" == "default" ] && default="${module}" # always prefer the default instance

        # see if the user has set this one
        [ "${socket}" == "${current_socket}" ] && gcs_var "o_mux_path" "${module}"

        # update the iselect
        echo "select_cd11mux${i}=${module} ${desc}"
        ((++i))
    done

    if [ -z "${default}" ]
    then
        gcs_err fatal "No data-mux-cd11 instances configured."
    else
        gcs_var "d_mux_path" "${default}"
    fi
}



# gcs_cd11mux_dereference()
#  Checks the value of "new_mux_path" to be sure it is valid, and dereferences it to the actual
#  socket path.
#   $1 -> "source" or "sink"
gcs_cd11mux_dereference() {
    local cfg socket

    source_or_sink="$1"

    cfg="${CONFIGDIR}/data-mux-cd11/${new_mux_path}.local"
    if [ ! -r "${cfg}" ]
    then
        gcs_err fatal "No matching data-mux-cd11 module (${new_mux_path}) found."
        return 1
    fi

    socket="$(gcs_get_varcf "${source_or_sink}_socket_path" "${cfg}")"
    if [ -z "${socket}" ]
    then
        gcs_err fatal "data-mux-cd11 module ${new_mux_path} has no socket."
        return 1
    fi

    new_mux_path="${socket}"
}



# vim: ts=4:sw=4:expandtab
