#!/bin/bash

#########################################
# Name: mkxpconf
#
# Summary: generate xpres config file
# contents, sent to stdout
#
# Description: uses input file to
# generate xpres config files from
# environment variables. Scripts can dynamically
# generate xpres configs w/o hard-coding device IDs
# and/or centralize configuration
#
# In the input file, set members of these
# associative arrays:
# SRC_ID : source IDs
# STR_ID : stream IDs (optional, uses 101 by default)
# XP_TFMT: time formats
# XP_OFMT: xpres data output formats
#
# Input file example:
#
#  !/bin/bash
#  # xp config definitions
#  # use mkxpconf to generate an xpres conf file
#  SRC_ID["sysmvc0"]="10000"
#  STR_ID["sysmvc0"]="101"
#  XP_TFMT["custom"]="%z"
#
# Author: k. headley
#
# Copyright 2014 MBARI
#
#########################################

#########################################
# Script configuration defaults
# casual users should not need to change
# anything below this section
#########################################
description="[Generate xpres config file content]"

#################################
# Script variable initialization
#################################
VERBOSE="FALSE"

unset SRC_ID
unset STR_ID
unset XP_OPT
unset XP_OFMT
unset XP_TFMT
unset MKX_IFILE
unset MKX_OFMT
unset MKX_TFMT

declare -A SRC_ID
declare -A STR_ID
declare -A XP_OPT
declare -A XP_OFMT
declare -A XP_TFMT

XP_OFMT["dat"]="\"%s.%d,%d,%s\n\",ftl,etf,dln,pas"
XP_OFMT["jit"]="\"%s.%d\n\",ftl,etf"
XP_TFMT["iso"]="%Y-%m-%d %H:%M:%S"
XP_TFMT["ems"]="%s"

STR_ID["dfl_str"]="101"

#################################
# Function Definitions
#################################
#################################
# name: sigTrap
# description: signal trap callback
# will interrupt 
# args: none
#################################
sigTrap(){
    exit 0;
}

#################################
# name: printUsage
# description: print use message
# args: none
#################################
printUsage(){
    echo
    echo "Description: $description"
    echo
    echo "usage: `basename $0` [options]"
	echo "Options:"
    echo "-f <file> : input file"
    echo "-o <ofmt> : output fmt [dat|jit]"
    echo "            (or user defined in input file)"
    echo "-t <tfmt> : time fmt [iso|ems]"
    echo             "(or user defined in input file)"
    echo "-v        : verbose output"
    echo "-h        : print use message"
    echo ""
    echo
}

########################################
# name: vout
# description: print verbose message to stderr
# args:
#     msg: message
########################################
vout(){
    if [ "$VERBOSE" == "TRUE" ]
    then
	echo "$1" >&2
    fi
}

########################################
# name: imsg
# description: echos with indent
# args:
#     msg: message
#  indent: indent level
########################################
imsg(){
  OIFS=$IFS
  IFS=""
  msg_pad="                                        "
  let "msg_indent=${1}"
  shift
  all="${@}"
  printf "%s%s\n" ${msg_pad:0:${msg_indent}} ${all}
  IFS=$OIFS
}

########################################
# name: msg
# description: echos with default indent
# args:
#     msg: message
########################################
msg(){
 imsg $MSG_INDENT "${*}"
}

########################################
# name: exitError
# description: print use message to stderr
# args:
#     msg:        error message
#     returnCode: exit status to return
########################################
exitError(){
    echo >&2
    echo "`basename $0`: error - $1" >&2
    echo >&2
    exit $2
}

########################################
# name: processCmdLine
# description: do command line processsing
# args:
#     args:       positional paramters
#     returnCode: none
########################################
processCmdLine(){
	OPTIND=1
	vout "`basename $0` all args[$*]"

    while getopts f:o:t:hv Option
	do
		vout "processing $Option[$OPTARG]"
		case $Option in
            f ) MKX_IFILE=${OPTARG}
            ;;
            o ) MKX_OFMT=${OPTARG}
            ;;
            t ) MKX_TFMT=${OPTARG}
            ;;
			v ) VERBOSE="TRUE"
			;;
			h)printUsage
				exit 0
			;;
			*) exit 0 # getopts outputs error message
			;;
		esac
	done
}

##########################
# Script main entry point
##########################


# Argument processing
# Accepts arguments from command line 
# or pipe/file redirect
# Comand line settings override config
# file settings

if [ -t 0 ]
then
	if [ "$#" -eq 0 ];then
		printUsage
		exit -1
	else
		processCmdLine $*
		let "i=$OPTIND-1"
		#while [ "${i}" -gt 0  ]
		#do
		#	shift
		#	let "i-=1"
		#done
	fi
else	
	declare -a cline_args
	let "i=1"
	while [ "$i" -le "$#" ]
	do
		cline_args[$i]="${@:$i:1}"
		let "i+=1"
	done

  	declare -a arg_array
	let "z=0"
	while read line ; do
		IFS=" " read opt val <<< $line
		if [ "${opt}" ] && [[ $opt != \#* ]]
		then
		    vout "opt $opt $z"
			arg_array[$z]=${opt}
			let "z+=1"
			if [ "${val}" ]
			then
				vout "val $val $z"
				arg_array[$z]=${val}
				let "z+=1"
			fi
		else 
			vout "skipping line $line"
		fi
	done
	
	# set default delimiter to 
	# newline for parsing/setting
	# positional parameters
	# [must restore after processing]
	IFSO=$IFS
	IFS=`echo` 
	set - ${arg_array[*]}
	
	# apply config file settings
	processCmdLine ${arg_array[*]}

	# apply command line settings
	# (override config file options)
	set - ${cline_args[*]}	
	processCmdLine ${cline_args[*]}

	# restore default delimiter
	IFS=$IFSO
	
	#let "i=$OPTIND-1"
	#while [ "${i}" -gt 0  ]
	#do
	#shift
	#let "i-=1"
	#done		
fi

vout "VERBOSE   : [$VERBOSE]"
vout "MKX_IFILE : [$MKX_IFILE]"
vout "MKX_OFMT  : [$MKX_OFMT]"
vout "MKX_TFMT  : [$MKX_TFMT]"


# validate input file (required
if [ "${MKX_IFILE}" ] && [ ! -f "${MKX_IFILE}" ]
then
    errExit "input file required, not found [$MKX_IFILE]" 1
fi

# source input file
. $MKX_IFILE

# validate output format
if [ -z ${XP_OFMT[$MKX_OFMT]} ]
then
    errExit "invalid output format [$MKX_OFMT]" 1
fi

if [ -z "${XP_TFMT[$MKX_TFMT]}" ]
then
    errExit "invalid time format [$MKX_TFMT]" 1
fi

# generate an output format option
# for each source ID
for key in `echo ${!SRC_ID[@]}`
do
XP_OPT["$key"]="-o ${SRC_ID[$key]},${STR_ID[$key]:-${STR_ID[dfl_str]}},${XP_OFMT[$MKX_OFMT]}"
done
# generate a time format option
XP_OPT["tfmt"]="-F \"${XP_TFMT[$MKX_TFMT]}\""

# echo the options to stdout
# [caller should redirect to file]
for key in `echo ${!XP_OPT[@]}`
do
echo ${XP_OPT[$key]}
done
exit 0

# call sigTrap on INT,TERM or EXIT
# trap sigTrap INT TERM EXIT

# reset trapped signals
# trap - INT TERM EXIT
