#!/bin/bash
# Bash arithmetic functions used so don't substitute plain sh
#
# Guralp Configuration System
#   Copyright (c) 2012 Guralp Systems Ltd. All rights reserved.
#
#   gdi2sacfile GDI to SAC file on NFS recorder

# Handle the navbar query without loading anything
if [ "X$1" == "X--navbar" ]
then
	echo "servicestop	Services"
	echo "servicessub/gdi2sacfile	gdi2sacfile"
	echo "gdi2sacfile/$3	$3"
	exit 0
fi

# Load support functions
script_dir=$(dirname $0)
. $script_dir/functions.sh
. $script_dir/svc_funcs.sh
. $script_dir/gdi-base_link.sh

name="$2"
sel="$3"

CFGFILE="$CONFIGDIR/$name/${sel}.local"
CTLFILE="$CONFIGDIR/$name/${sel}.ctl.local"
SRVBASE="$SERVDIR/$name"


do_read() {
    local mapnum entry have_channel_map src dest

    # Standard control info
    gcs_svc_read || return 1

    # Now the service type dependant variables

    ## Global
    gcs_var d_seconds_per_file	"900"
    gcs_var d_fname_fmt		"%Y%j-%h-sac/%Y%jT%H%MZ-%s-%c-%n-%l.sac"
    gcs_var d_mount_path	""
    gcs_var d_mount_options	""
    gcs_var d_uid		""
    gcs_var d_gid		""

    have_channel_map=0

    if [ -r "$CFGFILE" ]
    then
	gcs_var_o2 seconds_per_file	""
	gcs_var_o2 fname_fmt		""
	gcs_var_o2 mount_path		""
	gcs_var_o2 mount_options	""
	gcs_var_o2 uid			""
	gcs_var_o2 gid			""

	## channel map
	for entry in $(gcs_list_varcf2_sections "${CFGFILE}")
	do
	    if [ "${entry}" == "channel_map" ]
	    then
		have_channel_map=1
		break
	    fi
	done

	gcs_gdi_base_iselect "$(gcs_get_varcf2 "gdi_socket" "${CFGFILE}" "")" "sink"
    else
	gcs_gdi_base_iselect "" "sink"
    fi

    mapnum=0
    ignore_unmapped=0
    if [ "${have_channel_map}" -eq 0 ]
    then
        gcs_var "o_channel_map_mode" "automatic"
    else
        entry="$(gcs_get_varcf2 "reject_unfiltered_channels" "${CFGFILE}" "")"
        case "${entry}" in
        [Tt][Rr][Uu][Ee]|1)
            ignore_unmapped=1
            gcs_var "o_channel_map_mode" "manual"
            ;;
        *)
            gcs_var "o_channel_map_mode" "semi"
            ;;
        esac

        # Source command after done to maintain loop body in this context
        while read -r src dest
        do
            gcs_var "o_channel_map_src${mapnum}" "${src}"
            gcs_var "o_channel_map_dest${mapnum}" "${dest}"
            ((++mapnum))
        done < <(gcs_list_varcf2 "${CFGFILE}" "channel_map")
    fi

    if [ "${ignore_unmapped}" -eq 0 ]
    then
        while read -r src dest
        do
            [ -z "${src}" -o -z "${dest}" ] && continue

	    if [ -r "$CFGFILE" ]
	    then
		entry="$(gcs_get_varcf2 "${src}" "${CFGFILE}" "channel_map")"
		[ -z "${entry}" ] || continue
	    fi

            gcs_var "o_channel_map_src${mapnum}" "${src}"
            gcs_var "o_channel_map_dest${mapnum}" "${dest}"
            ((++mapnum))
        done < <(sacmap ${GDI_SOCKET_PATH})
    fi
}



do_check() {
    gcs_read_vars

    # Standard service control/info vars
    gcs_svc_check

    # Service dependant variables
    # Most of the checks are done by the main engine

    gcs_gdi_base_dereference "sink"

    if [ "${new_channel_map_mode}" == "manual" ]
    then
	check_table_not_empty "channel_map" "channel_map_src" \
			"No channels have been mapped."
    fi

    if [[ ! "$new_fname_fmt" =~ '%H' || ! "$new_fname_fmt" =~ '%M' ]]
    then
	gcs_err fname_fmt "Filename format must contain %H and %M somewhere"
    fi
}



do_write_channel_map() {
    local -i i
    local src dest

    for (( i = 0 ; i < $new_channel_map_rows ; i++ ))
    do
        eval src="\${new_channel_map_src${i}}"
        [ -z "${src}" ] && continue
        eval dest="\${new_channel_map_dest${i}}"
        gcs_set_varcf2 "${src}" "${CFGFILE}" "${dest}" "channel_map"
    done
}


do_write() {
    do_check
    if (( gcs_errors > 0 ))
    then
        return
    fi

    if gcs_truefalse "${new_delete:-false}"
    then
        gcs_svc_delete "$name" "$sel"
    fi

    # Standard service controls
    gcs_ensure_cfgfile_exists $CTLFILE
    gcs_set_varf DESC $CTLFILE "$desc"

    # Now the service type dependant variables
    gcs_ensure_cfgfile_exists "$CFGFILE"

    ## Global
    gcs_set_varcf2 "application_description" "${CFGFILE}" "${new_desc}"      ""
    gcs_set_varcf2 "seconds_per_file" "${CFGFILE}" "${new_seconds_per_file}" ""
    gcs_set_varcf2 "fname_fmt"        "${CFGFILE}" "${new_fname_fmt}"        ""
    gcs_set_varcf2 "mount_path"       "${CFGFILE}" "${new_mount_path}"       ""
    gcs_set_varcf2 "mount_options"    "${CFGFILE}" "${new_mount_options}"    ""
    gcs_set_varcf2 "uid"              "${CFGFILE}" "${new_uid}"              ""
    gcs_set_varcf2 "gid"              "${CFGFILE}" "${new_gid}"              ""

    gcs_set_varcf2 "gdi_socket"       "${CFGFILE}" "${new_gdi_socket}"       ""

    ## Channel map
    gcs_clear_varcf2_section "${CFGFILE}" "channel_map"

    case "${new_channel_map_mode}" in
    automatic)
        gcs_set_varcf2 "reject_unfiltered_channels" "${CFGFILE}" "" ""
        ;;
    semi)
        gcs_set_varcf2 "reject_unfiltered_channels" "${CFGFILE}" "False" ""
        do_write_channel_map
        ;;
    manual)
        gcs_set_varcf2 "reject_unfiltered_channels" "${CFGFILE}" "True" ""
        do_write_channel_map
        ;;
    esac

    # Update the service script
    gcs_update_svc "$name" "$sel" "$enable" "$desc" "$CFGFILE" "$CTLFILE" \
            "$SRVBASE" "$new_socket"
    
    gcs_svc_reload "$name" "$sel"
}



case "X$1" in
X--check)   do_check    ;;
X--write)   do_write    ;;
X--read)    do_read     ;;
*)          exit 1      ;;
esac

gcs_cleanup
exit 0

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