#!/bin/bash
#
# Guralp Configuration System
#   Copyright (c) 2009 Guralp Systems Ltd. All rights reserved.
#
#   gdi2miniseed configuration link functions
#     These functions simplify configuration of modules which are linked through the gdi2miniseed
#     converter. Rather than have the user specify the full path to the IPC socket, an iselect is
#     used to allow the user to select the converter from a list of modules. This list employs
#     the user's own description, to make the selection more user-friendly.



# gcs_gdi2miniseed_iselect()
#  This function prints the choices of converter module (gdi2miniseed) in a manner suitable for
#  an iselect, along with choosing a suitable default value for the miniseedout_dbdir variable.
#   $1 -> current setting of "miniseedout_dbdir"
gcs_gdi2miniseed_iselect() {
    local i default module cfg dbdir desc

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

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

        # 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
        [ "${dbdir}" == "$1" ] && gcs_var "o_miniseedout_dbdir" "${module}"

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

    if [ -z "${default}" ]
    then
        gcs_err fatal "No gdi2miniseed instances configured."
    else
        gcs_var "d_miniseedout_dbdir" "${default}"
    fi
}



# gcs_gdi2miniseed_dereference()
#  Checks the value of "new_miniseedout_dbdir" to be sure it is valid, and
#  dereferences it to the actual db path. Also sets miniseed_record_size.
gcs_gdi2miniseed_dereference() {
    local cfg dbdir

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

    dbdir="$(gcs_get_varcf2 "dbdir" "${cfg}" "")"
    if [ -z "${dbdir}" ]
    then
        gcs_err fatal "gdi2miniseed module ${new_miniseedout_dbdir} has no dbdir."
        return 1
    fi

    export miniseed_record_size="$(gcs_get_varcf2 "record_size" "${cfg}" "")"
    new_miniseedout_dbdir="${dbdir}"
}



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