#!/bin/bash

# Desc: Records gps data until midnight
# Author: Steven Baltakatei Sandoval; License: GPLv3+
# Usage: bkgpslog --output [output dir]

#==BEGIN Define script parameters==
PATH="/opt/bktei:$PATH"         # Add default baltakatei script install directory to PATH (necessary for other bk scripts)
SCRIPT_HOSTNAME=$(hostname)     # Save hostname of system running this script.
SCRIPT_VERSION="bkgpslog 0.0.1" # Define version of script.
SCRIPT_TIME_SHORT="$(date +%Y%m%dT%H%M%S%z)" # Save current date & time in ISO-8601 format.
SCRIPT_DATE_SHORT="$(date +%Y%m%d)"          # Save current date in ISO-8601 format.

declare -Ag appRollCall # Associative array for storing app status
declare -Ag fileRollCall # Associative array for storing file status
declare -Ag dirRollCall # Associative array for storing dir status

#===BEGIN Declare local script functions===
checkapp() {
    # Desc: If arg is a command, save result in assoc array 'appRollCall'
    # Usage: checkapp arg1 arg2 arg3 ...
    # Input: global assoc. array 'appRollCall'
    # Output: adds/updates key(value) to global assoc array 'appRollCall'
    local returnState    
    #echo "DEBUG:$(date +%S.%N)..Starting checkapp function."
    #echo "DEBUG:args: $@"
    #echo "DEBUG:returnState:$returnState"

    #===Process Args===
    for arg in "$@"; do
	#echo "DEBUG:processing arg:$arg"
	if command -v "$arg" 1>/dev/null 2>&1; then # Check if arg is a valid command
	    appRollCall[$arg]="true";
	    #echo "DEBUG:appRollCall[$arg]:"${appRollCall[$arg]}
	    if ! [ "$returnState" = "false" ]; then returnState="true"; fi
	else
	    appRollCall[$arg]="false"; returnState="false";
	fi
    done
    
    #for key in "${!appRollCall[@]}"; do echo "DEBUG:$key => ${appRollCall[$key]}"; done
    #echo "DEBUG:evaluating returnstate. returnState:"$returnState

    #===Determine function return code===
    if [ "$returnState" = "true" ]; then
	#echo "DEBUG:checkapp returns true for $arg";
	return 0;
    else
	#echo "DEBUG:checkapp returns false for $arg";
	return 1;
    fi
} # Check that app exists
checkfile() {
    # Desc: If arg is a file path, save result in assoc array 'fileRollCall'
    # Usage: checkfile arg1 arg2 arg3 ...
    # Input: global assoc. array 'fileRollCall'
    # Output: adds/updates key(value) to global assoc array 'fileRollCall';
    # Output: returns 0 if app found, 1 otherwise
    local returnState

    #===Process Args===
    for arg in "$@"; do
	#echo "DEBUG:processing arg:$arg"
	if [ -f "$arg" ]; then
	    fileRollCall["$arg"]="true";
	    #echo "DEBUG:fileRollCall[\"$arg\"]:"${fileRollCall["$arg"]}
	    if ! [ "$returnState" = "false" ]; then returnState="true"; fi
	else
	    fileRollCall["$arg"]="false"; returnState="false";
	fi
    done

    #for key in "${!fileRollCall[@]}"; do echo "DEBUG:fileRollCall key [$key] is:${fileRollCall[$key]}"; done
    #echo "DEBUG:evaluating returnstate. returnState:"$returnState
    
    #===Determine function return code===
    if [ "$returnState" = "true" ]; then
	#echo "DEBUG:checkapp returns true for $arg";
	return 0;
    else
	#echo "DEBUG:checkapp returns false for $arg";
	return 1;
    fi
} # Check that file exists
checkdir() {
    # Desc: If arg is a dir path, save result in assoc array 'dirRollCall'
    # Usage: checkdir arg1 arg2 arg3 ...
    # Input: global assoc. array 'dirRollCall'
    # Output: adds/updates key(value) to global assoc array 'dirRollCall';
    # Output: returns 0 if app found, 1 otherwise
    local returnState

    #===Process Args===
    for arg in "$@"; do
	#echo "DEBUG:processing arg:$arg"
	if [ -d "$arg" ]; then
	    dirRollCall["$arg"]="true";
	    #echo "DEBUG:dirRollCall[\"$arg\"]:"${dirRollCall["$arg"]}
	    if ! [ "$returnState" = "false" ]; then returnState="true"; fi
	elif [ "$arg" = "" ]; then
	    dirRollCall["$arg"]="false"; returnState="false";
	else
	    returnState="false";
	fi
    done

    #for key in "${!dirRollCall[@]}"; do echo "DEBUG:dirRollCall key [$key] is:${dirRollCall[$key]}"; done
    #echo "DEBUG:evaluating returnstate. returnState:"$returnState
    
    #===Determine function return code===
    if [ "$returnState" = "true" ]; then
	#echo "DEBUG:checkapp returns true for $arg";
	return 0;
    else
	#echo "DEBUG:checkapp returns false for $arg";
	return 1;
    fi
} # Check that dir exists

# Yell, Die, Try Three-Fingered Claw technique
# Ref/Attrib: https://stackoverflow.com/a/25515370
yell() { echo "$0: $*" >&2; }
die() { yell "$*"; exit 111; }
try() { "$@" || die "cannot $*"; }

echoerr() {
    echo "$@" 1>&2; # Define stderr echo function.
} # Define stderr message function.
showUsage() {
    echoerr "USAGE:"
    echoerr "    bkgpslog [ options ]"
    echoerr
    echoerr "OPTIONS:"
    echoerr "    -h, --help"
    echoerr "            Display help information."
    echoerr
    echoerr "    --version"
    echoerr "            Display script version."
    echoerr
    echoerr "    -v, --verbose"
    echoerr "            Display debugging info."
    echoerr
    echoerr "    -o, --output [ directory ]"
    echoerr "            Specify output directory to save logs."
} # Display information on how to use this script.
showVersion() {
    echoerr "$SCRIPT_VERSION"
} # Display script version.
vbm() {
    # Usage: vbm "DEBUG:verbose message here"
    # Description: Prints verbose message ("vbm") to stderr if OPTION_VERBOSE is set to "true".
    # Input:
    #   - OPTION_VERBOSE  variable set by processArguments function. (ex: "true", "false")
    #   - "$@"            positional arguments fed to this function.
    # Output: stderr
    # Script function dependencies: echoerr
    # External function dependencies: echo
    # Last modified: 2020-04-11T23:57Z
    # Last modified by: Steven Baltakatei Sandoval
    # License: GPLv3+
    # Ref./Attrib:

    if [ "$OPTION_VERBOSE" = "true" ]; then
	FUNCTION_TIME=$(date --iso-8601=ns); # Save current time in nano seconds.
	echoerr "[$FUNCTION_TIME] ""$*"; # Display argument text.
    fi

    # End function
    return 0; # Function finished.
} # Verbose message display function.
processArguments() {
    while [ ! $# -eq 0 ]; do   # While number of arguments ($#) is not (!) equal to (-eq) zero (0).
	#echoerr "DEBUG:Starting processArguments while loop."
	#echoerr "DEBUG:Provided arguments are:""$*"
	case "$1" in
	    -h | --help) showUsage; exit 1;; # Display usage.
	    --version) showVersion; exit 1;; # Show version
	    -v | --verbose) OPTION_VERBOSE="true"; vbm "DEBUG:Verbose mode enabled.";; # Enable verbose mode.
	    -o | --output) if [ -d "$2" ]; then DIROUT="$2"; vbm "DEBUG:DIROUT:$DIROUT"; shift; fi ;; # Define output directory.
	    *) echoerr "ERROR: Unrecognized argument."; exit 1;; # Handle unrecognized options.
	esac
	shift
    done
} # Argument Processing
timeUntilNextDay(){
    # Desc: Report seconds until next day.
    # Output: stdout: integer seconds until next day
    # Output: exit code 0 if stdout > 0; 1 if stdout = 0; 2 if stdout < 0
    # Usage: timeUntilNextDay
    # Usage: if ! myTTL="$(timeUntilNextDay)"; then yell "ERROR in if statement"; exit 1; fi
    local returnState TIME_CURRENT TIME_NEXT_DAY SECONDS_UNTIL_NEXT_DAY
    TIME_CURRENT="$(date --iso-8601=seconds)" ; # Produce `date`-parsable current timestamp with resolution of 1 second.
    TIME_NEXT_DAY="$(date -d "$TIME_CURRENT next day" --iso-8601=date)"; # Produce timestamp of beginning of tomorrow with resolution of 1 second.
    SECONDS_UNTIL_NEXT_DAY="$(( $(date +%s -d "$TIME_NEXT_DAY") - $(date +%s -d "$TIME_CURRENT") ))" ; # Calculate seconds until closest future midnight (res. 1 second).
    if [[ "$SECONDS_UNTIL_NEXT_DAY" -gt 0 ]]; then
	returnState="true";
    elif [[ "$SECONDS_UNTIL_NEXT_DAY" -eq 0 ]]; then
	returnState="WARNING_ZERO";
	yell "WARNING:Reported time until next day exactly zero.";
    elif [[ "$SECONDS_UNTIL_NEXT_DAY" -lt 0 ]]; then
	returnState="WARNING_NEGATIVE";
	yell "WARNING:Reported time until next day is negative.";
    fi

    try echo "$SECONDS_UNTIL_NEXT_DAY"; # Report
    
    #===Determine function return code===
    if [[ "$returnState" = "true" ]]; then
	return 0;
    elif [[ "$returnState" = "WARNING_ZERO" ]]; then
	return 1;
    elif [[ "$returnState" = "WARNING_NEGATIVE" ]]; then
	return 2;
    fi
} # Report seconds until next day
timeUntilNextHour(){
    # Desc: Report seconds until next hour
    # Output: stdout: integer seconds until next hour
    # Output: exit code 0 if stdout > 0; 1 if stdout = 0; 2 if stdout < 0
    # Usage: timeUntilNextHour
    # Usage: if ! myTTL="$(timeUntilNextHour)"; then yell "ERROR in if statement"; exit 1; fi
    local returnState TIME_CURRENT TIME_NEXT_HOUR SECONDS_UNTIL_NEXT_HOUR
    TIME_CURRENT="$(date --iso-8601=seconds)"; # Produce `date`-parsable current timestamp with resolution of 1 second.
    TIME_NEXT_HOUR="$(date -d "$TIME_CURRENT next hour" --iso-8601=hours)"; # Produce `date`-parsable current time stamp with resolution of 1 second.
    SECONDS_UNTIL_NEXT_HOUR="$(( $(date +%s -d "$TIME_NEXT_HOUR") - $(date +%s -d "$TIME_CURRENT") ))"; # Calculate seconds until next hour (res. 1 second).
    if [[ "$SECONDS_UNTIL_NEXT_HOUR" -gt 0 ]]; then
	returnState="true";
    elif [[ "$SECONDS_UNTIL_NEXT_HOUR" -eq 0 ]]; then
	returnState="WARNING_ZERO";
	yell "WARNING:Reported time until next hour exactly zero.";
    elif [[ "$SECONDS_UNTIL_NEXT_HOUR" -lt 0 ]]; then
	returnState="WARNING_NEGATIVE";
	yell "WARNING:Reported time until next hour is negative.";
    fi

    try echo "$SECONDS_UNTIL_NEXT_HOUR"; # Report
    
    #===Determine function return code===
    if [[ "$returnState" = "true" ]]; then
	return 0;
    elif [[ "$returnState" = "WARNING_ZERO" ]]; then
	return 1;
    elif [[ "$returnState" = "WARNING_NEGATIVE" ]]; then
	return 2;
    fi
} # Report seconds until next hour
dateTimeShort(){
    # Desc: Timestamp without separators (YYYYmmddTHHMMSS+zzzz)
    # Usage: dateTimeShort
    # Output: stdout: timestamp (ISO-8601, no separators)
    local TIME_CURRENT TIME_CURRENT_SHORT
    TIME_CURRENT="$(date --iso-8601=seconds)" ; # Produce `date`-parsable current timestamp with resolution of 1 second.
    TIME_CURRENT_SHORT="$(date -d "$TIME_CURRENT" +%Y%m%dT%H%M%S%z)"; # Produce separator-less current timestamp with resolution 1 second.
    echo "$TIME_CURRENT_SHORT";
} # Get date&time without separators
main() {
    processArguments "$@" # Process arguments.
    if checkapp gpspipe && checkdir "$DIROUT"; then

	# # Set script lifespan to end at start of next day
	# if ! scriptTTL="$(timeUntilNextDay)"; then
	#     if [[ "$scriptTTL" -eq 0 ]]; then
	# 	((scriptTTL++)); # Add 1 because 0 would cause 'timeout' to never timeout.
	#     else
	# 	yell "ERROR: timeUntilNextDay exit code $?"; exit 1;
	#     fi;
	# fi;

	# Set script lifespan to end at start of next hour
	if ! scriptTTL="$(timeUntilNextHour)"; then
	    if [[ "$scriptTTL" -eq 0 ]]; then
		((scriptTTL++)); # Add 1 because 0 would cause 'timeout' to never timeout.
	    else
		yell "ERROR: timeUntilNextHour exit code $?"; exit 1;
	    fi;
	fi;
        
	# Determine buffer lifespan
	bufferTTL="60";

	# Record gps data until script lifespan ends
	declare debugCounter; debugCounter="0"
	while [[ "$SECONDS" -lt "$scriptTTL" ]]; do
	    ((debugCounter++))
      	    # Determine output file paths (time is start of buffer period)
	    FILEOUT_BASENAME="$(dateTimeShort)""--P""$bufferTTL""S..""$SCRIPT_HOSTNAME""_location" ; # ISO-8601 YYYYmmddTHHMMSS+zzP[$bufferTTL]S
	    FILEOUT_NMEA="$FILEOUT_BASENAME".nmea ;
	    FILEOUT_GPX="$FILEOUT_BASENAME".gpx ;
	    FILEOUT_KML="$FILEOUT_BASENAME".kml ;
	    # Fill buffer
	    buffer="$(timeout "$bufferTTL""s" gpspipe -r)"; # Record gpspipe nmea data to buffer for bufferTTL seconds
	    # Process and save buffers
	    echo "$buffer"                                     > "$DIROUT"/"$FILEOUT_NMEA" & # Save NMEA format
	    echo "$buffer" | gpsbabel -i nmea -f - -o gpx -F - > "$DIROUT"/"$FILEOUT_GPX"  & # Save GPX format
	    echo "$buffer" | gpsbabel -i nmea -f - -o kml -F - > "$DIROUT"/"$FILEOUT_KML"  & # Save KML format
	    vbm "DEBUG:Completed buffer session $debugCounter ." 1>&2;
	    # Reset buffer and filenames
	    unset buffer FILEOUT_BASENAME FILEOUT_NMEA FILEOUT_GPX FILEOUT_KML;
	done
    fi
} # Main function.
#===END Declare local script functions===
#==END Define script parameters==


#==BEGIN Perform work and exit==
main "$@" # Run main function.
exit 0;
#==END Perform work and exit==


    
    #gpspipe -r -d -l -o "$DIROUT1"/"$FILEOUT1" ;