

#!/bin/bash

#########################################
# Name: xfrm.sh
#
# Summary: transform bos timestamps
#
# Description:
#
# Author: k. headley
#
# Copyright 2018 MBARI
#
#########################################

#########################################
# Script configuration defaults
# casual users should not need to change
# anything below this section
#########################################
description="Generate test data"

#################################
# Script variable initialization
#################################
VERBOSE="N"
unset DO_HELP

iso1806_regex="(^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3}Z)"
iso_ex="yyyy-mm-ddThh:hh:ss.sssZ,"
iso1806_len=${#iso_ex}
unset ID_START
unset OFILE

#################################
# Function Definitions
#################################

#################################
# name: printUsage
# description: print use message
# args: none
#################################
printUsage(){
echo
echo " Description: $description"
echo
echo " use: `basename $0` [options] file [file...]"
echo "  Options:"
echo "   -i n    : prepend ID field"
echo "   -o f    : output file"
echo "   -v      : verbose output    [$VERBOSE]"
echo "   -h      : print use message"
echo ""
echo
}

########################################
# name: vout
# description: print verbose message to stderr
# args:
#     msg: message
########################################
vout(){
if [ "${VERBOSE}" == "Y" ] || [ "${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 hi:o:v Option
do
vout "processing $Option[$OPTARG]"
case $Option in
i ) let "ID_START=$OPTARG"
;;
o ) OFILE=$OPTARG
;;
v ) VERBOSE="Y"
;;
h) DO_HELP="Y"
;;
*) exit 0 # getopts outputs error message
;;
esac
done
}

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

# Argument processing
# Accepts arguments from command line
# or pipe/file redirect

# process command line args
if [ "$#" -eq 0 ]
then
    printUsage
    #	exit -1
else
    # this ensures that quoted whitespace is preserved by getopts
    # note use of $@, in quotes

    # originally was processCmdLine $*
    processCmdLine "$@"
    let "i=$OPTIND-1"
    while [ "${i}" -gt 0  ]
    do
        shift
        let "i-=1"
    done
fi

echo ""
IFILES=$*
NFILES=$#

###########################
# debug output
vout "VERBOSE  : [${VERBOSE}]"
vout "NFILES   : [${NFILES}]"
vout "IFILES   : [${IFILES}]"
vout "OFILE    : [${OFILE}]"
vout "ID_START : [${ID_START}]"

###########################
# Run

# output help and exit
if [ ${DO_HELP} ] && [ ${DO_HELP} == "Y" ]
then
printUsage
exit 0
fi

if [ $IFILES ]
then
for file in $IFILES
do

odir=$(dirname ${file})
ofile=$(basename ${file})
ofile="${ofile%.[a-zA-Z0-9]*}-xfrm.csv"
opath="${odir}/${ofile}"

vout "${file} -> ${OFILE}"

while IFS= read line
    do
        if [ ${#line} -gt $iso1806_len ] && [[ ${line} =~ ${iso1806_regex} ]]
        then
            ts_iso=${line:0:19}
            ts_ms=${line:20:3}
            ts_esec=$(date -jf '%Y-%m-%dT%H:%M:%S' $ts_iso +%s)
            ts_eds="${ts_esec}${ts_ms}"
			if [ ${ID_START} ]
			then
				id="${ID_START},"
			fi
			if [ $OFILE ]
			then
				echo "$id$ts_eds,$line" >> $OFILE #$opath
            else
				echo "$id$ts_eds,$line"
            fi
            if [ ${ID_START} ]
            then
            let "ID_START+=1"
            fi
        fi
	done < $file

done
else
while IFS= read line
do
if [ ${#line} -gt $iso1806_len ] && [[ ${line} =~ ${iso1806_regex} ]]
then
ts_iso=${line:0:19}
ts_ms=${line:20:3}
ts_esec=$(date -jf '%Y-%m-%dT%H:%M:%S' $ts_iso +%s)
ts_eds="${ts_esec}${ts_ms}"
if [ ${ID_START} ]
then
id="${ID_START},"
fi
if [ $OFILE ]
then
echo "$id$ts_eds,$line" >> $OFILE #$opath
else
echo "$id$ts_eds,$line"
fi
if [ ${ID_START} ]
then
let "ID_START+=1"
fi
fi
done
fi
