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