fix(bkgpslog): Fix broken working dir name
[EVA-2020-02.git] / exec / bkgpslog
CommitLineData
032f4b05
SBS
1#!/bin/bash
2
8fbca23d
SBS
3# Desc: Records gps data until midnight
4# Author: Steven Baltakatei Sandoval; License: GPLv3+
aa2a49f1 5# Usage: bkgpslog -o [output dir]
032f4b05 6
8fbca23d 7#==BEGIN Define script parameters==
6c30388f
SBS
8## Logging Behavior parameters
9BUFFER_TTL="60"; # time between file writes
10SCRIPT_TTL="day"; # (day|hour)
aa2a49f1
SBS
11#### TZ="UTC"; export TZ; # Default time zone; overridden by '--time-zone=[str]' option
12DIR_TMP_DEFAULT="/dev/shm"; # Default parent of working directory
6c30388f 13
aa2a49f1
SBS
14SCRIPT_TIME_START=$(date +%Y%m%dT%H%M%S.%N);
15PATH="$HOME/.local/bin:$PATH"; # Add "$(systemd-path user-binaries)" path in case apps saved there
16SCRIPT_HOSTNAME=$(hostname); # Save hostname of system running this script.
17SCRIPT_VERSION="bkgpslog 0.1.0"; # Define version of script.
8fbca23d
SBS
18
19declare -Ag appRollCall # Associative array for storing app status
20declare -Ag fileRollCall # Associative array for storing file status
21declare -Ag dirRollCall # Associative array for storing dir status
17d49005 22declare -a recPubKeys # for processArguments function
77361307 23declare recipients # for main function
8fbca23d
SBS
24
25#===BEGIN Declare local script functions===
26checkapp() {
27 # Desc: If arg is a command, save result in assoc array 'appRollCall'
28 # Usage: checkapp arg1 arg2 arg3 ...
29 # Input: global assoc. array 'appRollCall'
30 # Output: adds/updates key(value) to global assoc array 'appRollCall'
31 local returnState
32 #echo "DEBUG:$(date +%S.%N)..Starting checkapp function."
33 #echo "DEBUG:args: $@"
34 #echo "DEBUG:returnState:$returnState"
35
36 #===Process Args===
37 for arg in "$@"; do
38 #echo "DEBUG:processing arg:$arg"
0b3dde05 39 if command -v "$arg" 1>/dev/null 2>&1; then # Check if arg is a valid command
8fbca23d
SBS
40 appRollCall[$arg]="true";
41 #echo "DEBUG:appRollCall[$arg]:"${appRollCall[$arg]}
42 if ! [ "$returnState" = "false" ]; then returnState="true"; fi
43 else
44 appRollCall[$arg]="false"; returnState="false";
45 fi
46 done
47
48 #for key in "${!appRollCall[@]}"; do echo "DEBUG:$key => ${appRollCall[$key]}"; done
49 #echo "DEBUG:evaluating returnstate. returnState:"$returnState
50
51 #===Determine function return code===
52 if [ "$returnState" = "true" ]; then
53 #echo "DEBUG:checkapp returns true for $arg";
54 return 0;
55 else
56 #echo "DEBUG:checkapp returns false for $arg";
57 return 1;
58 fi
59} # Check that app exists
60checkfile() {
61 # Desc: If arg is a file path, save result in assoc array 'fileRollCall'
62 # Usage: checkfile arg1 arg2 arg3 ...
63 # Input: global assoc. array 'fileRollCall'
64 # Output: adds/updates key(value) to global assoc array 'fileRollCall';
65 # Output: returns 0 if app found, 1 otherwise
66 local returnState
67
68 #===Process Args===
69 for arg in "$@"; do
70 #echo "DEBUG:processing arg:$arg"
71 if [ -f "$arg" ]; then
72 fileRollCall["$arg"]="true";
73 #echo "DEBUG:fileRollCall[\"$arg\"]:"${fileRollCall["$arg"]}
74 if ! [ "$returnState" = "false" ]; then returnState="true"; fi
75 else
76 fileRollCall["$arg"]="false"; returnState="false";
77 fi
78 done
79
80 #for key in "${!fileRollCall[@]}"; do echo "DEBUG:fileRollCall key [$key] is:${fileRollCall[$key]}"; done
81 #echo "DEBUG:evaluating returnstate. returnState:"$returnState
82
83 #===Determine function return code===
84 if [ "$returnState" = "true" ]; then
85 #echo "DEBUG:checkapp returns true for $arg";
86 return 0;
87 else
88 #echo "DEBUG:checkapp returns false for $arg";
89 return 1;
90 fi
91} # Check that file exists
92checkdir() {
93 # Desc: If arg is a dir path, save result in assoc array 'dirRollCall'
94 # Usage: checkdir arg1 arg2 arg3 ...
95 # Input: global assoc. array 'dirRollCall'
96 # Output: adds/updates key(value) to global assoc array 'dirRollCall';
97 # Output: returns 0 if app found, 1 otherwise
98 local returnState
99
100 #===Process Args===
101 for arg in "$@"; do
102 #echo "DEBUG:processing arg:$arg"
103 if [ -d "$arg" ]; then
104 dirRollCall["$arg"]="true";
105 #echo "DEBUG:dirRollCall[\"$arg\"]:"${dirRollCall["$arg"]}
106 if ! [ "$returnState" = "false" ]; then returnState="true"; fi
bcf09dcc 107 elif [ "$arg" = "" ]; then
8fbca23d 108 dirRollCall["$arg"]="false"; returnState="false";
bcf09dcc
SBS
109 else
110 returnState="false";
8fbca23d
SBS
111 fi
112 done
113
114 #for key in "${!dirRollCall[@]}"; do echo "DEBUG:dirRollCall key [$key] is:${dirRollCall[$key]}"; done
115 #echo "DEBUG:evaluating returnstate. returnState:"$returnState
116
117 #===Determine function return code===
118 if [ "$returnState" = "true" ]; then
119 #echo "DEBUG:checkapp returns true for $arg";
120 return 0;
121 else
122 #echo "DEBUG:checkapp returns false for $arg";
123 return 1;
124 fi
125} # Check that dir exists
032f4b05 126
c609b9c8
SBS
127# Yell, Die, Try Three-Fingered Claw technique
128# Ref/Attrib: https://stackoverflow.com/a/25515370
129yell() { echo "$0: $*" >&2; }
130die() { yell "$*"; exit 111; }
131try() { "$@" || die "cannot $*"; }
132
032f4b05
SBS
133echoerr() {
134 echo "$@" 1>&2; # Define stderr echo function.
135} # Define stderr message function.
136showUsage() {
137 echoerr "USAGE:"
94e094d1 138 echoerr " bkgpslog [ options ]"
032f4b05
SBS
139 echoerr
140 echoerr "OPTIONS:"
141 echoerr " -h, --help"
142 echoerr " Display help information."
143 echoerr
144 echoerr " --version"
145 echoerr " Display script version."
146 echoerr
147 echoerr " -v, --verbose"
148 echoerr " Display debugging info."
149 echoerr
17d49005
SBS
150 echoerr " -e, --encrypt"
151 echoerr " Encrypt output."
152 echoerr
153 echoerr " -r, --recipient [ pubkey string ]"
154 echoerr " Specify recipient."
155 echoerr
032f4b05
SBS
156 echoerr " -o, --output [ directory ]"
157 echoerr " Specify output directory to save logs."
17d49005 158 echoerr
408a342b
SBS
159 echoerr " -c, --compress"
160 echoerr " Compress output with gzip (before encryption if enabled)."
161 echoerr
17d49005 162 echoerr "EXAMPLE: (bash script lines)"
408a342b 163 echoerr "/bin/bash bkgpslog -e -c \\"
17d49005
SBS
164 echoerr "-r age1mrmfnwhtlprn4jquex0ukmwcm7y2nxlphuzgsgv8ew2k9mewy3rs8u7su5 \\"
165 echoerr "-r age1ala848kqrvxc88rzaauc6vc5v0fqrvef9dxyk79m0vjea3hagclswu0lgq \\"
166 echoerr "-o ~/Sync/Location"
032f4b05
SBS
167} # Display information on how to use this script.
168showVersion() {
169 echoerr "$SCRIPT_VERSION"
170} # Display script version.
171vbm() {
0b3dde05
SBS
172 # Usage: vbm "DEBUG:verbose message here"
173 # Description: Prints verbose message ("vbm") to stderr if OPTION_VERBOSE is set to "true".
174 # Input:
175 # - OPTION_VERBOSE variable set by processArguments function. (ex: "true", "false")
176 # - "$@" positional arguments fed to this function.
177 # Output: stderr
178 # Script function dependencies: echoerr
179 # External function dependencies: echo
180 # Last modified: 2020-04-11T23:57Z
181 # Last modified by: Steven Baltakatei Sandoval
182 # License: GPLv3+
183 # Ref./Attrib:
184
185 if [ "$OPTION_VERBOSE" = "true" ]; then
186 FUNCTION_TIME=$(date --iso-8601=ns); # Save current time in nano seconds.
187 echoerr "[$FUNCTION_TIME] ""$*"; # Display argument text.
032f4b05 188 fi
0b3dde05
SBS
189
190 # End function
191 return 0; # Function finished.
032f4b05
SBS
192} # Verbose message display function.
193processArguments() {
194 while [ ! $# -eq 0 ]; do # While number of arguments ($#) is not (!) equal to (-eq) zero (0).
d6896d3b
SBS
195 #echoerr "DEBUG:Starting processArguments while loop."
196 #echoerr "DEBUG:Provided arguments are:""$*"
032f4b05 197 case "$1" in
c1bbf9f7 198 -h | --help) showUsage; exit 1;; # Display usage.
032f4b05 199 --version) showVersion; exit 1;; # Show version
c1bbf9f7 200 -v | --verbose) OPTION_VERBOSE="true"; vbm "DEBUG:Verbose mode enabled.";; # Enable verbose mode.
6c30388f 201 -o | --output) if [ -d "$2" ]; then DIR_OUT="$2"; vbm "DEBUG:DIR_OUT:$DIR_OUT"; shift; fi ;; # Define output directory.
17d49005
SBS
202 -e | --encrypt) OPTION_ENCRYPT="true"; vbm "DEBUG:Encrypted output mode enabled.";;
203 -r | --recipient) # Add 'age' recipient via public key string
77361307 204 recPubKeys+=("$2"); vbm "pubkey added:""$2"; shift;;
408a342b 205 -c | --compress) OPTION_COMPRESS="true"; vbm "DEBUG:Compressed output mode enabled.";;
6c30388f 206 -z | --time-zone) try setTimeZoneEV "$1";;
032f4b05
SBS
207 *) echoerr "ERROR: Unrecognized argument."; exit 1;; # Handle unrecognized options.
208 esac
209 shift
210 done
211} # Argument Processing
6c30388f
SBS
212setTimeZoneEV(){
213 # Desc: Set time zone environment variable TZ
214 # Usage: setTimeZoneEV arg1
215 # Input: arg1: 'date'-compatible timezone string (ex: "America/New_York")
216 # TZDIR env var (optional; default: "/usr/share/zoneinfo")
217 # Output: exports TZ
218 # exit code 0 on success
219 # exit code 1 on incorrect number of arguments
220 # exit code 2 if unable to validate arg1
221 # Depends: yell, printenv, bash 5
222 # Tested on: Debian 10
223 ARG1="$1"
224 local tzDir returnState
225 if ! [[ $# -eq 1 ]]; then
226 yell "ERROR:Invalid argument count.";
227 return 1;
228 fi
229
230 # Read TZDIR env var if available
231 if printenv TZDIR 1>/dev/null 2>&1; then
232 tzDir="$(printenv TZDIR)";
233 else
234 tzDir="/usr/share/zoneinfo";
235 fi
236
237 # Validate TZ string
238 if ! [[ -f "$tzDir"/"$ARG1" ]]; then
239 yell "ERROR:Invalid time zone argument.";
240 return 2;
241 else
242 # Export ARG1 as TZ environment variable
243 TZ="$ARG1" && export TZ && returnState="true";
244 fi
245
246 # Determine function return code
247 if [ "$returnState" = "true" ]; then
248 return 0;
249 fi
250} # Exports TZ environment variable
c2aaff78
SBS
251timeUntilNextDay(){
252 # Desc: Report seconds until next day.
253 # Output: stdout: integer seconds until next day
8fbca23d 254 # Output: exit code 0 if stdout > 0; 1 if stdout = 0; 2 if stdout < 0
c2aaff78
SBS
255 # Usage: timeUntilNextDay
256 # Usage: if ! myTTL="$(timeUntilNextDay)"; then yell "ERROR in if statement"; exit 1; fi
257 local returnState TIME_CURRENT TIME_NEXT_DAY SECONDS_UNTIL_NEXT_DAY
8fbca23d 258 TIME_CURRENT="$(date --iso-8601=seconds)" ; # Produce `date`-parsable current timestamp with resolution of 1 second.
c2aaff78
SBS
259 TIME_NEXT_DAY="$(date -d "$TIME_CURRENT next day" --iso-8601=date)"; # Produce timestamp of beginning of tomorrow with resolution of 1 second.
260 SECONDS_UNTIL_NEXT_DAY="$(( $(date +%s -d "$TIME_NEXT_DAY") - $(date +%s -d "$TIME_CURRENT") ))" ; # Calculate seconds until closest future midnight (res. 1 second).
261 if [[ "$SECONDS_UNTIL_NEXT_DAY" -gt 0 ]]; then
262 returnState="true";
263 elif [[ "$SECONDS_UNTIL_NEXT_DAY" -eq 0 ]]; then
264 returnState="WARNING_ZERO";
265 yell "WARNING:Reported time until next day exactly zero.";
266 elif [[ "$SECONDS_UNTIL_NEXT_DAY" -lt 0 ]]; then
267 returnState="WARNING_NEGATIVE";
268 yell "WARNING:Reported time until next day is negative.";
269 fi
270
271 try echo "$SECONDS_UNTIL_NEXT_DAY"; # Report
272
273 #===Determine function return code===
274 if [[ "$returnState" = "true" ]]; then
275 return 0;
276 elif [[ "$returnState" = "WARNING_ZERO" ]]; then
277 return 1;
278 elif [[ "$returnState" = "WARNING_NEGATIVE" ]]; then
279 return 2;
280 fi
281} # Report seconds until next day
282timeUntilNextHour(){
283 # Desc: Report seconds until next hour
284 # Output: stdout: integer seconds until next hour
285 # Output: exit code 0 if stdout > 0; 1 if stdout = 0; 2 if stdout < 0
286 # Usage: timeUntilNextHour
287 # Usage: if ! myTTL="$(timeUntilNextHour)"; then yell "ERROR in if statement"; exit 1; fi
288 local returnState TIME_CURRENT TIME_NEXT_HOUR SECONDS_UNTIL_NEXT_HOUR
289 TIME_CURRENT="$(date --iso-8601=seconds)"; # Produce `date`-parsable current timestamp with resolution of 1 second.
290 TIME_NEXT_HOUR="$(date -d "$TIME_CURRENT next hour" --iso-8601=hours)"; # Produce `date`-parsable current time stamp with resolution of 1 second.
291 SECONDS_UNTIL_NEXT_HOUR="$(( $(date +%s -d "$TIME_NEXT_HOUR") - $(date +%s -d "$TIME_CURRENT") ))"; # Calculate seconds until next hour (res. 1 second).
292 if [[ "$SECONDS_UNTIL_NEXT_HOUR" -gt 0 ]]; then
8fbca23d 293 returnState="true";
c2aaff78 294 elif [[ "$SECONDS_UNTIL_NEXT_HOUR" -eq 0 ]]; then
8fbca23d 295 returnState="WARNING_ZERO";
c2aaff78
SBS
296 yell "WARNING:Reported time until next hour exactly zero.";
297 elif [[ "$SECONDS_UNTIL_NEXT_HOUR" -lt 0 ]]; then
8fbca23d 298 returnState="WARNING_NEGATIVE";
c2aaff78 299 yell "WARNING:Reported time until next hour is negative.";
8fbca23d 300 fi
032f4b05 301
c2aaff78 302 try echo "$SECONDS_UNTIL_NEXT_HOUR"; # Report
8fbca23d
SBS
303
304 #===Determine function return code===
305 if [[ "$returnState" = "true" ]]; then
306 return 0;
307 elif [[ "$returnState" = "WARNING_ZERO" ]]; then
308 return 1;
309 elif [[ "$returnState" = "WARNING_NEGATIVE" ]]; then
310 return 2;
311 fi
c2aaff78 312} # Report seconds until next hour
8fbca23d
SBS
313dateTimeShort(){
314 # Desc: Timestamp without separators (YYYYmmddTHHMMSS+zzzz)
315 # Usage: dateTimeShort
316 # Output: stdout: timestamp (ISO-8601, no separators)
c2aaff78 317 local TIME_CURRENT TIME_CURRENT_SHORT
8fbca23d
SBS
318 TIME_CURRENT="$(date --iso-8601=seconds)" ; # Produce `date`-parsable current timestamp with resolution of 1 second.
319 TIME_CURRENT_SHORT="$(date -d "$TIME_CURRENT" +%Y%m%dT%H%M%S%z)"; # Produce separator-less current timestamp with resolution 1 second.
320 echo "$TIME_CURRENT_SHORT";
6c30388f
SBS
321} # Get YYYYmmddTHHMMSS±zzzz
322dateShort(){
323 # Desc: Date without separators (YYYYmmdd)
324 # Usage: dateShort
325 # Output: stdout: date (ISO-8601, no separators)
326 local TIME_CURRENT DATE_CURRENT_SHORT
327 TIME_CURRENT="$(date --iso-8601=seconds)" ; # Produce `date`-parsable current timestamp with resolution of 1 second.
328 DATE_CURRENT_SHORT="$(date -d "$TIME_CURRENT" +%Y%m%d)"; # Produce separator-less current date with resolution 1 day.
329 echo "$DATE_CURRENT_SHORT";
330} # Get YYYYmmdd
331timeDuration(){
332 # Desc: Output approximate time duration string before given time (default:current date)
333 # Ref/Attrib: ISO-8601:2004(E), §4.4.4.2 Representations of time intervals by duration and context information
334 # Note: "1 month" ("P1M") is assumed to be "30 days" (see ISO-8601:2004(E), §2.2.1.2)
335 # Usage: timeDuration [arg1] ([arg2])
336 # Input: arg1: seconds as base 10 integer >= 0 (ex: 3601)
337 # arg2: precision level (optional; default=2)
338 # Output: stdout: ISO-8601 duration string (ex: "P1H1S", "P2Y10M15DT10H30M20S")
339 # Example: 'timeDuration 111111 3' yields 'P1DT6H51M'
340 # Depends: date 8 (gnucoreutils)
341 local returnState fullHours fullMinutes fullSeconds;
342 ARG1="$1";
343 ARG2="$2";
344 precision=2; # set default precision
345 returnState="true"; # set default return state
346
347 # Check that between one and two arguments is supplied
348 if ! { [[ $# -ge 1 ]] && [[ $# -le 2 ]]; }; then
349 yell "ERROR:Invalid number of arguments:$# . Exiting.";
350 returnState="ERROR_INPUT"; fi
351
352 # Check that arg1 provided
353 if [[ $# -ge 1 ]]; then
354 # Check that arg1 is a positive integer
355 if [[ "$ARG1" =~ ^[[:digit:]]+$ ]]; then
356 arg1Valid="true";
357 else
358 yell "ERROR:ARG1 not a digit.";
359 returnState="ERROR_INPUT";
360 arg1Valid="false";
361 fi
362 else
363 yell "ERROR:No argument provided. Exiting.";
364 exit 1;
365 fi
366
367 # Consider whether arg2 was provided
368 if [[ $# -eq 2 ]]; then
369 # Check that the second arg is a positive integer
370 if [[ "$ARG2" =~ ^[[:digit:]]+$ ]] && [[ "ARG2" -gt 0 ]]; then
371 arg2Valid="true";
372 precision="$ARG2";
373 else
374 yell "ERROR:ARG2 not a positive integer. (is $ARG2 ). Leaving early.";
375 returnState="ERROR_INPUT";
376 arg2Valid="false";
377 fi;
378 else
379 arg2Valid="false";
380 fi;
381
382 remainder="$ARG1" ; # seconds
383 ## Calculate full years Y, update remainder
384 fullYears=$(( remainder / (365*24*60*60) ));
385 remainder=$(( remainder - (fullYears*365*24*60*60) ));
386 ## Calculate full months M, update remainder
387 fullMonths=$(( remainder / (30*24*60*60) ));
388 remainder=$(( remainder - (fullMonths*30*24*60*60) ));
389 ## Calculate full days D, update remainder
390 fullDays=$(( remainder / (24*60*60) ));
391 remainder=$(( remainder - (fullDays*24*60*60) ));
392 ## Calculate full hours H, update remainder
393 fullHours=$(( remainder / (60*60) ));
394 remainder=$(( remainder - (fullHours*60*60) ));
395 ## Calculate full minutes M, update remainder
396 fullMinutes=$(( remainder / (60) ));
397 remainder=$(( remainder - (fullMinutes*60) ));
398 ## Calculate full seconds S, update remainder
399 fullSeconds=$(( remainder / (1) ));
400 remainder=$(( remainder - (remainder*1) ));
401 ## Check which fields filled
402 if [[ $fullYears -gt 0 ]]; then hasYears="true"; else hasYears="false"; fi
403 if [[ $fullMonths -gt 0 ]]; then hasMonths="true"; else hasMonths="false"; fi
404 if [[ $fullDays -gt 0 ]]; then hasDays="true"; else hasDays="false"; fi
405 if [[ $fullHours -gt 0 ]]; then hasHours="true"; else hasHours="false"; fi
406 if [[ $fullMinutes -gt 0 ]]; then hasMinutes="true"; else hasMinutes="false"; fi
407 if [[ $fullSeconds -gt 0 ]]; then hasSeconds="true"; else hasSeconds="false"; fi
408
409 ## Determine which fields to display (see ISO-8601:2004 §4.4.3.2)
410 witherPrecision="false"
411
412 ### Years
413 if $hasYears && [[ $precision -gt 0 ]]; then
414 displayYears="true";
415 witherPrecision="true";
416 else
417 displayYears="false";
418 fi;
419 if $witherPrecision; then ((precision--)); fi;
420
421 ### Months
422 if $hasMonths && [[ $precision -gt 0 ]]; then
423 displayMonths="true";
424 witherPrecision="true";
425 else
426 displayMonths="false";
427 fi;
428 if $witherPrecision && [[ $precision -gt 0 ]]; then
429 displayMonths="true";
430 fi;
431 if $witherPrecision; then ((precision--)); fi;
432
433 ### Days
434 if $hasDays && [[ $precision -gt 0 ]]; then
435 displayDays="true";
436 witherPrecision="true";
437 else
438 displayDays="false";
439 fi;
440 if $witherPrecision && [[ $precision -gt 0 ]]; then
441 displayDays="true";
442 fi;
443 if $witherPrecision; then ((precision--)); fi;
444
445 ### Hours
446 if $hasHours && [[ $precision -gt 0 ]]; then
447 displayHours="true";
448 witherPrecision="true";
449 else
450 displayHours="false";
451 fi;
452 if $witherPrecision && [[ $precision -gt 0 ]]; then
453 displayHours="true";
454 fi;
455 if $witherPrecision; then ((precision--)); fi;
456
457 ### Minutes
458 if $hasMinutes && [[ $precision -gt 0 ]]; then
459 displayMinutes="true";
460 witherPrecision="true";
461 else
462 displayMinutes="false";
463 fi;
464 if $witherPrecision && [[ $precision -gt 0 ]]; then
465 displayMinutes="true";
466 fi;
467 if $witherPrecision; then ((precision--)); fi;
468
469 ### Seconds
470
471 if $hasSeconds && [[ $precision -gt 0 ]]; then
472 displaySeconds="true";
473 witherPrecision="true";
474 else
475 displaySeconds="false";
476 fi;
477 if $witherPrecision && [[ $precision -gt 0 ]]; then
478 displaySeconds="true";
479 fi;
480 if $witherPrecision; then ((precision--)); fi;
481
482
483
484 ## Determine whether or not the "T" separator is needed to separate date and time elements
485 if ( $displayHours || $displayMinutes || $displaySeconds); then
486 displayDateTime="true"; else displayDateTime="false"; fi
487
488 ## Construct duration output string
489 OUTPUT="P"
490 if $displayYears; then
491 OUTPUT=$OUTPUT$fullYears"Y"; fi
492 if $displayMonths; then
493 OUTPUT=$OUTPUT$fullMonths"M"; fi
494 if $displayDays; then
495 OUTPUT=$OUTPUT$fullDays"D"; fi
496 if $displayDateTime; then
497 OUTPUT=$OUTPUT"T"; fi
498 if $displayHours; then
499 OUTPUT=$OUTPUT$fullHours"H"; fi
500 if $displayMinutes; then
501 OUTPUT=$OUTPUT$fullMinutes"M"; fi
502 if $displaySeconds; then
503 OUTPUT=$OUTPUT$fullSeconds"S"; fi
504
505 ## Output duration string to stdout
506 if [[ "$returnState" = "true" ]]; then echo "$OUTPUT"; fi
507
508 #===Determine function return code===
509 if [ "$returnState" = "true" ]; then
510 return 0;
511 else
512 echo "$returnState" 1>&2;
513 return 1;
514 fi
515
516} # Get duration (ex: PT10M4S )
517displayMissing() {
518 # Desc: Displays missing apps, files, and dirs
519 # Usage: displayMissing
520 # Input: associative arrays: appRollCall, fileRollCall, dirRollCall
521 # Output: stderr messages
522 #==BEGIN Display errors==
523 #===BEGIN Display Missing Apps===
524 missingApps="Missing apps :"
525 #for key in "${!appRollCall[@]}"; do echo "DEBUG:$key => ${appRollCall[$key]}"; done
526 for key in "${!appRollCall[@]}"; do
527 value="${appRollCall[$key]}"
528 if [ "$value" = "false" ]; then
529 #echo "DEBUG:Missing apps: $key => $value";
530 missingApps="$missingApps""$key "
531 appMissing="true"
532 fi
533 done
534 if [ "$appMissing" = "true" ]; then # Only indicate if an app is missing.
535 echo "$missingApps" 1>&2;
536 fi
537 #===END Display Missing Apps===
538
539 #===BEGIN Display Missing Files===
540 missingFiles="Missing files:"
541 #for key in "${!fileRollCall[@]}"; do echo "DEBUG:$key => ${fileRollCall[$key]}"; done
542 for key in "${!fileRollCall[@]}"; do
543 value="${fileRollCall[$key]}"
544 if [ "$value" = "false" ]; then
545 #echo "DEBUG:Missing files: $key => $value";
546 missingFiles="$missingFiles""$key "
547 fileMissing="true"
548 fi
549 done
550 if [ "$fileMissing" = "true" ]; then # Only indicate if an app is missing.
551 echo "$missingFiles" 1>&2;
552 fi
553 #===END Display Missing Files===
554
555 #===BEGIN Display Missing Directories===
556 missingDirs="Missing dirs:"
557 #for key in "${!dirRollCall[@]}"; do echo "DEBUG:$key => ${dirRollCall[$key]}"; done
558 for key in "${!dirRollCall[@]}"; do
559 value="${dirRollCall[$key]}"
560 if [ "$value" = "false" ]; then
561 #echo "DEBUG:Missing dirs: $key => $value";
562 missingDirs="$missingDirs""$key "
563 dirMissing="true"
564 fi
565 done
566 if [ "$dirMissing" = "true" ]; then # Only indicate if an dir is missing.
567 echo "$missingDirs" 1>&2;
568 fi
569 #===END Display Missing Directories===
570
571 #==END Display errors==
572} # Display missing apps, files, dirs
573setScriptTTL() {
574 #Desc: Sets script TTL
575 #Usage: setScriptTTL arg1
576 #Input: arg1: "day" or "hour"
577 #Output: scriptTTL
578 #Depends: timeUntilNextHour or timeUntilNextDay
579 local ARG1
580 ARG1="$1"
581 if [[ "$ARG1" = "day" ]]; then
582 # Set script lifespan to end at start of next day
583 if ! scriptTTL="$(timeUntilNextDay)"; then
584 if [[ "$scriptTTL" -eq 0 ]]; then
585 ((scriptTTL++)); # Add 1 because 0 would cause 'timeout' to never timeout.
586 else
587 yell "ERROR: timeUntilNextDay exit code $?"; exit 1;
588 fi;
589 fi;
590 elif [[ "$ARG1" = "hour" ]]; then
591 # Set script lifespan to end at start of next hour
592 if ! scriptTTL="$(timeUntilNextHour)"; then
593 if [[ "$scriptTTL" -eq 0 ]]; then
594 ((scriptTTL++)); # Add 1 because 0 would cause 'timeout' to never timeout.
595 else
596 yell "ERROR: timeUntilNextHour exit code $?"; exit 1;
597 fi;
598 fi;
599 else
600 yell "ERROR:Invalid argument for setScriptTTL function."; exit 1;
601 fi
602} # Seconds until next (day|hour).
032f4b05 603main() {
0b3dde05 604 processArguments "$@" # Process arguments.
6c30388f 605
aa2a49f1
SBS
606 # Determine working directory
607 if [[ -d "$DIR_TMP_DEFAULT" ]]; then
608 DIR_TMP_BASE="$DIR_TMP_DEFAULT"; # Use default working directory parent (ex: '/dev/shm')
609 #### elif [[ -d /tmp ]]; then
610 #### yell "WARNING:/dev/shm not available. Falling back to /tmp .";
611 #### DIR_TMP_BASE="/tmp";
612 else
613 yell "ERROR:No valid working directory available. Exiting.";
614 exit 1;
615 fi
616 DIR_TMP="$DIR_TMP_BASE"/"$SCRIPT_TIME_START""..bkgpslog"; # Define working directory for temproary files
617
6c30388f 618 # Set output encryption and compression option strings
17d49005
SBS
619 if [[ "$OPTION_ENCRYPT" = "true" ]]; then # Check if encryption option active.
620 if checkapp age; then # Check that age is available.
621 for pubkey in "${recPubKeys[@]}"; do # Validate recipient pubkey strings by forming test message
622 vbm "DEBUG:Testing pubkey string:$pubkey"
408a342b 623 if echo "butts" | age -a -r "$pubkey" 1>/dev/null; then
77361307
SBS
624 # Form age recipient string
625 recipients="$recipients""-r $pubkey ";
408a342b 626 vbm "Added pubkey for forming age recipient string:""$pubkey";
77361307 627 vbm "DEBUG:recipients:""$recipients";
408a342b
SBS
628 else
629 yell "ERROR:Exit code ""$?"". Invalid recipient pubkey string. Exiting."; exit 1;
77361307 630 fi
17d49005 631 done
77361307 632 vbm "DEBUG:Finished processing recPubKeys array";
408a342b 633 # Form age command string
c97313bf 634 CMD_ENCRYPT="age ""$recipients ";
408a342b 635 CMD_ENCRYPT_SUFFIX=".age";
17d49005
SBS
636 else
637 yell "ERROR:Encryption enabled but \"age\" not found. Exiting."; exit 1;
638 fi
408a342b 639 else
c97313bf 640 CMD_ENCRYPT="tee /dev/null ";
408a342b
SBS
641 CMD_ENCRYPT_SUFFIX="";
642 vbm "DEBUG:Encryption not enabled."
17d49005 643 fi
408a342b
SBS
644 if [[ "$OPTION_COMPRESS" = "true" ]]; then # Check if compression option active
645 if checkapp gzip; then # Check if gzip available
c97313bf 646 CMD_COMPRESS="gzip ";
408a342b
SBS
647 CMD_COMPRESS_SUFFIX=".gz";
648 else
649 yell "ERROR:Compression enabled but \"gzip\" not found. Exiting."; exit 1;
286d9825 650 fi
408a342b 651 else
c97313bf 652 CMD_COMPRESS="tee /dev/null ";
408a342b
SBS
653 CMD_COMPRESS_SUFFIX="";
654 vbm "DEBUG:Compression not enabled."
655 fi
032f4b05 656
6c30388f
SBS
657 # Check that critical apps and dirs are available, displag missing ones.
658 if ! checkapp gpspipe tar && ! checkdir "$DIR_OUT" "/dev/shm"; then
659 yell "ERROR:Critical components missing.";
660 displayMissing; yell "Exiting."; exit 1; fi
661
662 # Set script lifespan
663 setScriptTTL "$SCRIPT_TTL";
664
665 # File name substring: encoded bufferTTL
666 bufferTTL_STR="$(timeDuration $BUFFER_TTL)";
667
668 # Init temp working dir
669 try mkdir "$DIR_TMP" && vbm "DEBUG:Working dir creatd at:$DIR_TMP"
670
671 # Initialize 'tar' archive
672 ## Define output tar path (note: each day gets *one* tar file (Ex: "20200731..hostname_location.[.gpx.gz].tar"))
673 PATHOUT_TAR="$DIR_OUT"/"$(dateShort)".."$SCRIPT_HOSTNAME""_location""$CMD_COMPRESS_SUFFIX""$CMD_ENCRYPT_SUFFIX".tar
674 ## Write bkgpslog version to DIR_TMP/VERSION
675 echo "$0"" Version:""$SCRIPT_VERSION" >> "$DIR_TMP/VERSION" && vbm "DEBUG:VERSION created."
676 ## Create empty tar archive at PATHOUT_TAR
aa2a49f1 677 try tar --create --directory="$DIR_TMP" --file="$PATHOUT_TAR" --files-from=/dev/null && vbm "DEBUG:""$PATHOUT_TAR"" created."
6c30388f
SBS
678 ## Append VERSION file to PATHOUT_TAR
679 try tar --append --directory="$DIR_TMP" --file="$PATHOUT_TAR" "VERSION" && vbm "DEBUG:VERSION added to $PATHOUT_TAR"
680
681 # Record gps data until script lifespan ends
682 declare debugCounter; debugCounter="0"; # set debug counter
683 timeStart=$(dateTimeShort); # Note start time
684 while [[ "$SECONDS" -lt "$scriptTTL" ]]; do
685 # Determine file paths (time is start of buffer period)
686 FILEOUT_BASENAME="$timeStart""--""$bufferTTL_STR""..""$SCRIPT_HOSTNAME""_location" ; # ISO-8601 YYYYmmddTHHMMSS+zzP[$bufferTTL]S
aa2a49f1 687 ## Files saved to DIR_TMP
6c30388f
SBS
688 PATHOUT_NMEA="$DIR_TMP"/"$FILEOUT_BASENAME".nmea"$CMD_COMPRESS_SUFFIX""$CMD_ENCRYPT_SUFFIX" ;
689 PATHOUT_GPX="$DIR_TMP"/"$FILEOUT_BASENAME".gpx"$CMD_COMPRESS_SUFFIX""$CMD_ENCRYPT_SUFFIX" ;
690 PATHOUT_KML="$DIR_TMP"/"$FILEOUT_BASENAME".kml"$CMD_COMPRESS_SUFFIX""$CMD_ENCRYPT_SUFFIX" ;
691 ## Files saved to disk (DIR_OUT)
692 ### one file per day (Ex: "20200731..hostname_location.[.gpx.gz].tar")
693 PATHOUT_TAR="$DIR_OUT"/"$(dateShort)".."$SCRIPT_HOSTNAME""_location""$CMD_COMPRESS_SUFFIX""$CMD_ENCRYPT_SUFFIX".tar
694 # Define GPS conversion commands
695 CMD_CONV_NMEA="tee /dev/null " ; # tee as passthrough
696 CMD_CONV_GPX="gpsbabel -i nmea -f - -o gpx -F - " ; # convert NMEA to GPX
697 CMD_CONV_KML="gpsbabel -i nmea -f - -o kml -F - " ; # convert NMEA to KML
698 # Fill Bash variable buffer
699 bufferBash="$(timeout "$BUFFER_TTL""s" gpspipe -r)"; # Record gpspipe nmea data to buffer for bufferTTL seconds
700 # Process bufferBash, save secured chunk set to DIR_TMP
701 echo "$bufferBash" | $CMD_CONV_NMEA | $CMD_COMPRESS | $CMD_ENCRYPT > "$PATHOUT_NMEA" & # Create NMEA file (secured if requested)
702 echo "$bufferBash" | $CMD_CONV_GPX | $CMD_COMPRESS | $CMD_ENCRYPT > "$PATHOUT_GPX" & # Create GPX file (secured if requested)
703 echo "$bufferBash" | $CMD_CONV_KML | $CMD_COMPRESS | $CMD_ENCRYPT > "$PATHOUT_KML" & # Create KML file (secured if requested)
704 vbm "DEBUG:Completed buffer session $debugCounter ." 1>&2;
705 # Append each secured chunk in memory dir (DIR_TMP) to file on disk (PATHOUT_TAR in DIR_OUT)
706 try tar --append --directory="$(dirname $"PATHOUT_NMEA")" --file="$PATHOUT_TAR" "$(basename "$PATHOUT_NMEA")" && \
707 vbm "DEBUG:Appended NMEA location data $PATHOUT_NMEA to $PATHOUT_TAR";
708 try tar --append --directory="$(dirname $"PATHOUT_GPX")" --file="$PATHOUT_TAR" "$(basename "$PATHOUT_GPX")" && \
709 vbm "DEBUG:Appended GPX location data $PATHOUT_GPX to $PATHOUT_TAR";
710 try tar --append --directory="$(dirname $"PATHOUT_KML")" --file="$PATHOUT_TAR" "$(basename "$PATHOUT_KML")" && \
711 vbm "DEBUG:Appended KML location $PATHOUT_KML to $PATHOUT_TAR";
712 # Remove secured chunks from DIR_TMP
713 try rm "$PATHOUT_NMEA" "$PATHOUT_NMEA" "$PATHOUT_NMEA";
714 # Reset buffer and filenames
715 unset bufferBash FILEOUT_BASENAME PATHOUT_NMEA PATHOUT_GPX PATHOUT_KML PATHOUT_TAR;
716 ((debugCounter++))
717 done
8fbca23d
SBS
718} # Main function.
719#===END Declare local script functions===
720#==END Define script parameters==
032f4b05
SBS
721
722
8fbca23d
SBS
723#==BEGIN Perform work and exit==
724main "$@" # Run main function.
725exit 0;
726#==END Perform work and exit==