2 # Desc: Compresses, encrypts, and writes stdin every 5 seconds
4 #==BEGIN Define script parameters==
5 #===BEGIN Initialize variables===
7 # Logging Behavior parameters
8 bufferTTL
="300"; # Time-to-live (seconds) for each buffer round
9 scriptTTL_TE
="day"; # Time element at the end of which script terminates
10 dirTmpDefault
="/dev/shm"; # Default parent of working directory
13 scriptName
="bklog"; # Define basename of script file.
14 scriptVersion
="0.1.5"; # Define version of script.
15 scriptURL
="https://gitlab.com/baltakatei/ninfacyzga-01"; # Define wesite hosting this script.
16 scriptTimeStart
="$(date +%Y%m%dT%H%M%S.%N)"; # YYYYmmddTHHMMSS.NNNNNNNNN
17 scriptHostname
=$
(hostname
); # Save hostname of system running this script.
18 PATH
="$HOME/.local/bin:$PATH"; # Add "$(systemd-path user-binaries)" path in case user apps saved there
19 ageVersion
="1.0.0-beta2"; # Define version of age (encryption program)
20 ageURL
="https://github.com/FiloSottile/age/releases/tag/v1.0.0-beta2"; # Define website hosting age.
23 declare -a buffer
# array for storing while read buffer
24 declare -a argRecPubKeys
# array for processArguments function
25 declare -a recPubKeysValid
# array for storing both '-r' and '-R' recipient pubkeys
26 declare -a recPubKeysValidStatic
# for storing '-r' recipient pubkeys
27 declare -a argProcStrings argProcFileExts
# for storing buffer processing strings (ex: "gpsbabel -i nmea -f - -o gpx -F - ")
28 declare -Ag appRollCall
# Associative array for storing app status
29 declare -Ag fileRollCall
# Associative array for storing file status
30 declare -Ag dirRollCall
# Associative array for storing dir status
31 declare -a procStrings procFileExts
# Arrays for storing processing commands and resulting output file extensions
34 optionVerbose
=""; optionEncrypt
=""; dirOut
=""; optionEncrypt
=""; dir_tmp
="";
35 cmd_compress
="";cmd_compress_suffix
=""; cmd_encrypt
=""; cmd_encrypt_suffix
="";
37 #===END Initialize variables===
39 #===BEGIN Declare local script functions===
40 yell
() { echo "$0: $*" >&2; } #o Yell, Die, Try Three-Fingered Claw technique
41 die
() { yell
"$*"; exit 111; } #o Ref/Attrib: https://stackoverflow.com/a/25515370
42 try
() { "$@" || die
"cannot $*"; } #o
44 while [ ! $# -eq 0 ]; do # While number of arguments ($#) is not (!) equal to (-eq) zero (0).
46 -v |
--verbose) optionVerbose
="true"; vbm
"DEBUG:Verbose mode enabled.";; # Enable verbose mode.
47 -h |
--help) showUsage
; exit 1;; # Display usage.
48 --version) showVersion
; exit 1;; # Show version
49 -o |
--output) if [ -d "$2" ]; then dirOut
="$2"; vbm
"DEBUG:dirOut:$dirOut"; shift; fi ;; # Define output directory.
50 -e |
--encrypt) optionEncrypt
="true"; vbm
"DEBUG:Encrypted output mode enabled.";; # Enable encryption
51 -r |
--recipient) optionRecipients
="true"; argRecPubKeys
+=("$2"); vbm
"STATUS:pubkey added:""$2"; shift;; # Add recipients
52 -c |
--compress) optionCompress
="true"; vbm
"DEBUG:Compressed output mode enabled.";; # Enable compression
53 -z |
--time-zone) try setTimeZoneEV
"$2"; shift;; # Set timestamp timezone
54 -t |
--temp-dir) optionTmpDir
="true" && argTempDirPriority
="$2"; shift;; # Set time zone
55 -R |
--recipient-dir) optionRecipients
="true"; optionRecDir
="true" && argRecDir
="$2"; shift;; # Add recipient watch dir
56 -b |
--buffer-ttl) optionCustomBufferTTL
="true" && argCustomBufferTTL
="$2"; shift;; # Set custom buffer period (default: 300 seconds)
57 -B |
--script-ttl) optionCustomScriptTTL_TE
="true" && argCustomScriptTTL_TE
="$2"; shift;; # Set custom script TTL (default: "day")
58 -p |
--process-string) optionProcString
="true" && argProcStrings
+=("$2") && argProcFileExts
+=("$3") && vbm
"STATUS:file extension \"$2\" for output of processing string added:\"$3\""; shift; shift;;
59 -l |
--label) optionLabel
="true" && argLabel
="$2"; vbm
"DEBUG:Custom label received:$argLabel"; shift;;
60 -w |
--store-raw) optionStoreRaw
="true" && argRawFileExt
="$2"; vbm
"DEBUG:Raw stdin file extension received:$argRawFileExt"; shift;;
61 -W |
--no-store-raw) optionNoStoreRaw
="true"; vbm
"DEBUG:Option selected to not store raw stdin data."; shift;;
62 *) yell
"ERROR: Unrecognized argument: $1"; yell
"STATUS:All arguments:$*"; exit 1;; # Handle unrecognized options.
66 } # Argument Processing
68 # Description: Prints verbose message ("vbm") to stderr if optionVerbose is set to "true".
69 # Usage: vbm "DEBUG:verbose message here"
74 # Depends: bash 5.0.3, echo 8.30, date 8.30
76 if [ "$optionVerbose" = "true" ]; then
77 functionTime
=$
(date --iso-8601=ns
); # Save current time in nano seconds.
78 echo "[$functionTime] ""$*" 1>&2; # Display argument text.
82 return 0; # Function finished.
83 } # Displays message if optionVerbose true
85 # Desc: If arg is a command, save result in assoc array 'appRollCall'
86 # Usage: checkapp arg1 arg2 arg3 ...
88 # Input: global assoc. array 'appRollCall'
89 # Output: adds/updates key(value) to global assoc array 'appRollCall'
95 if command -v "$arg" 1>/dev
/null
2>&1; then # Check if arg is a valid command
96 appRollCall
[$arg]="true";
97 if ! [ "$returnState" = "false" ]; then returnState
="true"; fi;
99 appRollCall
[$arg]="false"; returnState
="false";
103 #===Determine function return code===
104 if [ "$returnState" = "true" ]; then
109 } # Check that app exists
111 # Desc: If arg is a file path, save result in assoc array 'fileRollCall'
112 # Usage: checkfile arg1 arg2 arg3 ...
114 # Input: global assoc. array 'fileRollCall'
115 # Output: adds/updates key(value) to global assoc array 'fileRollCall';
116 # Output: returns 0 if app found, 1 otherwise
117 # Depends: bash 5.0.3
122 if [ -f "$arg" ]; then
123 fileRollCall
["$arg"]="true";
124 if ! [ "$returnState" = "false" ]; then returnState
="true"; fi;
126 fileRollCall
["$arg"]="false"; returnState
="false";
130 #===Determine function return code===
131 if [ "$returnState" = "true" ]; then
136 } # Check that file exists
138 # Desc: If arg is a dir path, save result in assoc array 'dirRollCall'
139 # Usage: checkdir arg1 arg2 arg3 ...
141 # Input: global assoc. array 'dirRollCall'
142 # Output: adds/updates key(value) to global assoc array 'dirRollCall';
143 # Output: returns 0 if app found, 1 otherwise
144 # Depends: Bash 5.0.3
149 if [ -d "$arg" ]; then
150 dirRollCall
["$arg"]="true";
151 if ! [ "$returnState" = "false" ]; then returnState
="true"; fi
153 dirRollCall
["$arg"]="false"; returnState
="false";
157 #===Determine function return code===
158 if [ "$returnState" = "true" ]; then
163 } # Check that dir exists
165 # Desc: Displays missing apps, files, and dirs
166 # Usage: displayMissing
168 # Input: associative arrays: appRollCall, fileRollCall, dirRollCall
169 # Output: stderr: messages indicating missing apps, file, or dirs
170 # Depends: bash 5, checkAppFileDir()
171 local missingApps value appMissing missingFiles fileMissing
172 local missingDirs dirMissing
174 #==BEGIN Display errors==
175 #===BEGIN Display Missing Apps===
176 missingApps
="Missing apps :";
177 #for key in "${!appRollCall[@]}"; do echo "DEBUG:$key => ${appRollCall[$key]}"; done
178 for key
in "${!appRollCall[@]}"; do
179 value
="${appRollCall[$key]}";
180 if [ "$value" = "false" ]; then
181 #echo "DEBUG:Missing apps: $key => $value";
182 missingApps
="$missingApps""$key ";
186 if [ "$appMissing" = "true" ]; then # Only indicate if an app is missing.
187 echo "$missingApps" 1>&2;
190 #===END Display Missing Apps===
192 #===BEGIN Display Missing Files===
193 missingFiles
="Missing files:";
194 #for key in "${!fileRollCall[@]}"; do echo "DEBUG:$key => ${fileRollCall[$key]}"; done
195 for key
in "${!fileRollCall[@]}"; do
196 value
="${fileRollCall[$key]}";
197 if [ "$value" = "false" ]; then
198 #echo "DEBUG:Missing files: $key => $value";
199 missingFiles
="$missingFiles""$key ";
203 if [ "$fileMissing" = "true" ]; then # Only indicate if an app is missing.
204 echo "$missingFiles" 1>&2;
207 #===END Display Missing Files===
209 #===BEGIN Display Missing Directories===
210 missingDirs
="Missing dirs:";
211 #for key in "${!dirRollCall[@]}"; do echo "DEBUG:$key => ${dirRollCall[$key]}"; done
212 for key
in "${!dirRollCall[@]}"; do
213 value
="${dirRollCall[$key]}";
214 if [ "$value" = "false" ]; then
215 #echo "DEBUG:Missing dirs: $key => $value";
216 missingDirs
="$missingDirs""$key ";
220 if [ "$dirMissing" = "true" ]; then # Only indicate if an dir is missing.
221 echo "$missingDirs" 1>&2;
224 #===END Display Missing Directories===
226 #==END Display errors==
227 } # Display missing apps, files, dirs
230 # Desc: Appends [processed] file to tar
231 # Usage: appendFileTar [file path] [name of file to be inserted] [tar path] [temp dir] ([process cmd])
233 # Input: arg1: path of file to be (processed and) written
234 # arg2: name to use for file inserted into tar
235 # arg3: tar archive path (must exist first)
236 # arg4: temporary working dir
237 # arg5: (optional) command string to process file (ex: "gpsbabel -i nmea -f - -o kml -F - ")
238 # Output: file written to disk
239 # Example: decrypt multiple large files in parallel
240 # appendFileTar /tmp/largefile1.gpg "largefile1" $HOME/archive.tar /tmp "gpg --decrypt" &
241 # appendFileTar /tmp/largefile2.gpg "largefile2" $HOME/archive.tar /tmp "gpg --decrypt" &
242 # appendFileTar /tmp/largefile3.gpg "largefile3" $HOME/archive.tar /tmp "gpg --decrypt" &
243 # Depends: bash 5.0.3, tar 1.30, cat 8.30, yell()
244 local fn fileName tarPath tmpDir
248 #yell "DEBUG:STATUS:$fn:Started appendFileTar()."
251 if ! [ -z "$2" ]; then fileName
="$2"; else yell
"ERROR:$fn:Not enough arguments."; exit 1; fi
252 # Check tar path is a file
253 if [ -f "$3" ]; then tarPath
="$3"; else yell
"ERROR:$fn:Tar archive arg not a file:$3"; exit 1; fi
255 if ! [ -z "$4" ]; then tmpDir
="$4"; else yell
"ERROR:$fn:No temporary working dir set."; exit 1; fi
256 # Set command strings
257 if ! [ -z "$5" ]; then cmd1
="$5"; else cmd1
="cat "; fi # command string
259 # Input command string
262 # Write to temporary working dir
263 eval "$cmd0 | $cmd1" > "$tmpDir"/"$fileName";
266 try
tar --append --directory="$tmpDir" --file="$tarPath" "$fileName";
267 #yell "DEBUG:STATUS:$fn:Finished appendFileTar()."
268 } # Append [processed] file to Tar archive
270 # Desc: Checks if string is an age-compatible pubkey
271 # Usage: checkAgePubkey [str pubkey]
273 # Input: arg1: string
274 # Output: return code 0: string is age-compatible pubkey
275 # return code 1: string is NOT an age-compatible pubkey
276 # age stderr (ex: there is stderr if invalid string provided)
277 # Depends: age (v0.1.0-beta2; https://github.com/FiloSottile/age/releases/tag/v1.0.0-beta2 )
281 if echo "test" | age
-a -r "$argPubkey" 1>/dev
/null
; then
288 # Desc: Date without separators (YYYYmmdd)
289 # Usage: dateShort ([str date])
291 # Input: arg1: 'date'-parsable timestamp string (optional)
292 # Output: stdout: date (ISO-8601, no separators)
293 # Depends: bash 5.0.3, date 8.30, yell()
294 local argTime timeCurrent timeInput dateCurrentShort
298 timeCurrent
="$(date --iso-8601=seconds)" ; # Produce `date`-parsable current timestamp with resolution of 1 second.
299 # Decide to parse current or supplied date
300 ## Check if time argument empty
301 if [[ -z "$argTime" ]]; then
302 ## T: Time argument empty, use current time
303 timeInput
="$timeCurrent";
305 ## F: Time argument exists, validate time
306 if date --date="$argTime" 1>/dev
/null
2>&1; then
307 ### T: Time argument is valid; use it
308 timeInput
="$argTime";
310 ### F: Time argument not valid; exit
311 yell
"ERROR:Invalid time argument supplied. Exiting."; exit 1;
314 # Construct and deliver separator-les date string
315 dateCurrentShort
="$(date -d "$timeInput" +%Y%m%d)"; # Produce separator-less current date with resolution 1 day.
316 echo "$dateCurrentShort";
319 # Desc: Set time zone environment variable TZ
320 # Usage: setTimeZoneEV arg1
322 # Input: arg1: 'date'-compatible timezone string (ex: "America/New_York")
323 # TZDIR env var (optional; default: "/usr/share/zoneinfo")
325 # exit code 0 on success
326 # exit code 1 on incorrect number of arguments
327 # exit code 2 if unable to validate arg1
328 # Depends: yell(), printenv 8.30, bash 5.0.3
329 # Tested on: Debian 10
330 local tzDir returnState argTimeZone
333 if ! [[ $# -eq 1 ]]; then
334 yell
"ERROR:Invalid argument count.";
338 # Read TZDIR env var if available
339 if printenv TZDIR
1>/dev
/null
2>&1; then
340 tzDir
="$(printenv TZDIR)";
342 tzDir
="/usr/share/zoneinfo";
346 if ! [[ -f "$tzDir"/"$argTimeZone" ]]; then
347 yell
"ERROR:Invalid time zone argument.";
350 # Export ARG1 as TZ environment variable
351 TZ
="$argTimeZone" && export TZ
&& returnState
="true";
354 # Determine function return code
355 if [ "$returnState" = "true" ]; then
358 } # Exports TZ environment variable
362 cmd | bklog [ options ]
366 Display help information.
368 Display script version.
370 Display debugging info.
373 -r, --recipient [ string pubkey ]
374 Specify recipient. May be age or ssh pubkey.
375 May be specified multiple times for multiple pubkeys.
376 See https://github.com/FiloSottile/age
377 -o, --output [ path dir ]
378 Specify output directory to save logs. This option is required
380 -p, --process-string [ filter command ] [ output file extension]
381 Specify how to create and name a processed version of the stdin.
382 For example, if stdin is 'nmea' location data:
384 -p "gpsbabel -i nmea -f - -o gpx -F - " ".gpx"
386 This option would cause the stdin to 'bklog' to be piped into
387 the 'gpsbabel' command, interpreted as 'nmea' data, converted
388 into 'gpx' format, and then appended to the output tar file
389 as a file with a '.gpx' extension.
390 This option may be specified multiple times in order to output
391 results of multiple different processing methods.
392 -l, --label [ string ]
393 Specify a label to be included in all output file names.
394 Ex: 'location' if stdin is location data.
395 -w, --store-raw [ file extension ]
396 Specify file extension of file within output tar that contains
397 raw stdin data. The default behavior is to always save raw stdin
398 data in a '.stdin' file. Example usage when 'bklog' receives
399 'nmea' data from 'gpspipe -r':
403 Stdin data is saved in a '.nmea' file within the output tar.
405 Do not store raw stdin in output tar.
407 Compress output with gzip (before encryption if enabled).
409 Specify time zone. (ex: "America/New_York")
410 -t, --temp-dir [path dir]
411 Specify parent directory for temporary working directory.
413 -R, --recipient-dir [path dir]
414 Specify directory containing files whose first lines are
415 to be interpreted as pubkey strings (see '-r' option).
416 -b, --buffer-ttl [integer]
417 Specify custom buffer period in seconds (default: 300 seconds)
418 -B, --script-ttl [time element string]
419 Specify custom script time-to-live in seconds (default: "day")
420 Valid values: "day", "hour"
422 EXAMPLE: (bash script lines)
423 $ gpspipe -r | /bin/bash bklog -v -e -c -z "UTC" -t "/dev/shm" \
424 -r age1mrmfnwhtlprn4jquex0ukmwcm7y2nxlphuzgsgv8ew2k9mewy3rs8u7su5 \
425 -r age1ala848kqrvxc88rzaauc6vc5v0fqrvef9dxyk79m0vjea3hagclswu0lgq \
426 -R ~/.config/bklog/recipients -w ".nmea" -b 300 -B "day" \
427 -o ~/Sync/Logs -l "location" \
428 -p "gpsbabel -i nmea -f - -o gpx -F - " ".gpx" \
429 -p "gpsbabel -i nmea -f - -o kml -F - " ".kml"
431 } # Display information on how to use this script.
433 yell
"$scriptVersion"
434 } # Display script version.
436 # Desc: Given seconds, output ISO-8601 duration string
437 # Ref/Attrib: ISO-8601:2004(E), §4.4.4.2 Representations of time intervals by duration and context information
438 # Note: "1 month" ("P1M") is assumed to be "30 days" (see ISO-8601:2004(E), §2.2.1.2)
439 # Usage: timeDuration [1:seconds] ([2:precision])
441 # Input: arg1: seconds as base 10 integer >= 0 (ex: 3601)
442 # arg2: precision level (optional; default=2)
443 # Output: stdout: ISO-8601 duration string (ex: "P1H1S", "P2Y10M15DT10H30M20S")
444 # exit code 0: success
445 # exit code 1: error_input
446 # exit code 2: error_unknown
447 # Example: 'timeDuration 111111 3' yields 'P1DT6H51M'
448 # Depends: date 8, bash 5, yell,
449 local argSeconds argPrecision precision returnState remainder
450 local fullYears fullMonths fullDays fullHours fullMinutes fullSeconds
451 local hasYears hasMonths hasDays hasHours hasMinutes hasSeconds
452 local witherPrecision output
453 local displayYears displayMonths displayDays displayHours displayMinutes displaySeconds
455 argSeconds
="$1"; # read arg1 (seconds)
456 argPrecision
="$2"; # read arg2 (precision)
457 precision
=2; # set default precision
459 # Check that between one and two arguments is supplied
460 if ! { [[ $# -ge 1 ]] && [[ $# -le 2 ]]; }; then
461 yell
"ERROR:Invalid number of arguments:$# . Exiting.";
462 returnState
="error_input"; fi
464 # Check that argSeconds provided
465 if [[ $# -ge 1 ]]; then
466 ## Check that argSeconds is a positive integer
467 if [[ "$argSeconds" =~ ^
[[:digit
:]]+$
]]; then
470 yell
"ERROR:argSeconds not a digit.";
471 returnState
="error_input";
474 yell
"ERROR:No argument provided. Exiting.";
478 # Consider whether argPrecision was provided
479 if [[ $# -eq 2 ]]; then
480 # Check that argPrecision is a positive integer
481 if [[ "$argPrecision" =~ ^
[[:digit
:]]+$
]] && [[ "$argPrecision" -gt 0 ]]; then
482 precision
="$argPrecision";
484 yell
"ERROR:argPrecision not a positive integer. (is $argPrecision ). Leaving early.";
485 returnState
="error_input";
491 remainder
="$argSeconds" ; # seconds
492 ## Calculate full years Y, update remainder
493 fullYears
=$
(( remainder
/ (365*24*60*60) ));
494 remainder
=$
(( remainder
- (fullYears
*365*24*60*60) ));
495 ## Calculate full months M, update remainder
496 fullMonths
=$
(( remainder
/ (30*24*60*60) ));
497 remainder
=$
(( remainder
- (fullMonths
*30*24*60*60) ));
498 ## Calculate full days D, update remainder
499 fullDays
=$
(( remainder
/ (24*60*60) ));
500 remainder
=$
(( remainder
- (fullDays
*24*60*60) ));
501 ## Calculate full hours H, update remainder
502 fullHours
=$
(( remainder
/ (60*60) ));
503 remainder
=$
(( remainder
- (fullHours
*60*60) ));
504 ## Calculate full minutes M, update remainder
505 fullMinutes
=$
(( remainder
/ (60) ));
506 remainder
=$
(( remainder
- (fullMinutes
*60) ));
507 ## Calculate full seconds S, update remainder
508 fullSeconds
=$
(( remainder
/ (1) ));
509 remainder
=$
(( remainder
- (remainder
*1) ));
510 ## Check which fields filled
511 if [[ $fullYears -gt 0 ]]; then hasYears
="true"; else hasYears
="false"; fi
512 if [[ $fullMonths -gt 0 ]]; then hasMonths
="true"; else hasMonths
="false"; fi
513 if [[ $fullDays -gt 0 ]]; then hasDays
="true"; else hasDays
="false"; fi
514 if [[ $fullHours -gt 0 ]]; then hasHours
="true"; else hasHours
="false"; fi
515 if [[ $fullMinutes -gt 0 ]]; then hasMinutes
="true"; else hasMinutes
="false"; fi
516 if [[ $fullSeconds -gt 0 ]]; then hasSeconds
="true"; else hasSeconds
="false"; fi
518 ## Determine which fields to display (see ISO-8601:2004 §4.4.3.2)
519 witherPrecision
="false"
522 if $hasYears && [[ $precision -gt 0 ]]; then
524 witherPrecision
="true";
526 displayYears
="false";
528 if $witherPrecision; then ((precision--
)); fi;
531 if $hasMonths && [[ $precision -gt 0 ]]; then
532 displayMonths
="true";
533 witherPrecision
="true";
535 displayMonths
="false";
537 if $witherPrecision && [[ $precision -gt 0 ]]; then
538 displayMonths
="true";
540 if $witherPrecision; then ((precision--
)); fi;
543 if $hasDays && [[ $precision -gt 0 ]]; then
545 witherPrecision
="true";
549 if $witherPrecision && [[ $precision -gt 0 ]]; then
552 if $witherPrecision; then ((precision--
)); fi;
555 if $hasHours && [[ $precision -gt 0 ]]; then
557 witherPrecision
="true";
559 displayHours
="false";
561 if $witherPrecision && [[ $precision -gt 0 ]]; then
564 if $witherPrecision; then ((precision--
)); fi;
567 if $hasMinutes && [[ $precision -gt 0 ]]; then
568 displayMinutes
="true";
569 witherPrecision
="true";
571 displayMinutes
="false";
573 if $witherPrecision && [[ $precision -gt 0 ]]; then
574 displayMinutes
="true";
576 if $witherPrecision; then ((precision--
)); fi;
580 if $hasSeconds && [[ $precision -gt 0 ]]; then
581 displaySeconds
="true";
582 witherPrecision
="true";
584 displaySeconds
="false";
586 if $witherPrecision && [[ $precision -gt 0 ]]; then
587 displaySeconds
="true";
589 if $witherPrecision; then ((precision--
)); fi;
591 ## Determine whether or not the "T" separator is needed to separate date and time elements
592 if ( $displayHours ||
$displayMinutes ||
$displaySeconds); then
593 displayDateTime
="true"; else displayDateTime
="false"; fi
595 ## Construct duration output string
597 if $displayYears; then
598 output
=$output$fullYears"Y"; fi
599 if $displayMonths; then
600 output
=$output$fullMonths"M"; fi
601 if $displayDays; then
602 output
=$output$fullDays"D"; fi
603 if $displayDateTime; then
604 output
=$output"T"; fi
605 if $displayHours; then
606 output
=$output$fullHours"H"; fi
607 if $displayMinutes; then
608 output
=$output$fullMinutes"M"; fi
609 if $displaySeconds; then
610 output
=$output$fullSeconds"S"; fi
612 ## Output duration string to stdout
613 echo "$output" && returnState
="true";
615 #===Determine function return code===
616 if [ "$returnState" = "true" ]; then
618 elif [ "$returnState" = "error_input" ]; then
622 yell
"ERROR:Unknown";
626 } # Get duration (ex: PT10M4S )
628 magicInitWorkingDir
() {
629 # Desc: Determine temporary working directory from defaults or user input
630 # Usage: magicInitWorkingDir
631 # Input: vars: optionTmpDir, argTempDirPriority, dirTmpDefault
632 # Input: vars: scriptTimeStart
633 # Output: vars: dir_tmp
634 # Depends: bash 5.0.3, processArguments(), vbm(), yell()
635 # Parse '-t' option (user-specified temporary working dir)
636 ## Set dir_tmp_parent to user-specified value if specified
639 if [[ "$optionTmpDir" = "true" ]]; then
640 if [[ -d "$argTempDirPriority" ]]; then
641 dir_tmp_parent
="$argTempDirPriority";
643 yell
"WARNING:Specified temporary working directory not valid:$argTempDirPriority";
644 exit 1; # Exit since user requires a specific temp dir and it is not available.
647 ## Set dir_tmp_parent to default or fallback otherwise
648 if [[ -d "$dirTmpDefault" ]]; then
649 dir_tmp_parent
="$dirTmpDefault";
650 elif [[ -d /tmp
]]; then
651 yell
"WARNING:$dirTmpDefault not available. Falling back to /tmp .";
652 dir_tmp_parent
="/tmp";
654 yell
"ERROR:No valid working directory available. Exiting.";
658 ## Set dir_tmp using dir_tmp_parent and nonce (scriptTimeStart)
659 dir_tmp
="$dir_tmp_parent"/"$scriptTimeStart""..bkgpslog" && vbm
"DEBUG:Set dir_tmp to:$dir_tmp"; # Note: removed at end of main().
661 magicInitCheckTar
() {
662 # Desc: Initializes or checks output tar
663 # input: vars: dirOut, bufferTTL, cmd_encrypt_suffix, cmd_compress_suffix
664 # input: vars: scriptHostname
665 # output: vars: pathout_tar
666 # depends: Bash 5.0.3, vbm(), dateShort(), checkMakeTar(), magicWriteVersion()
669 pathout_tar
="$dirOut"/"$(dateShort "$
(date --date="$bufferTTL seconds ago" --iso-8601=seconds
)")"..
"$scriptHostname""$label""$cmd_compress_suffix""$cmd_encrypt_suffix".
tar && \
670 vbm
"STATUS:Set pathout_tar to:$pathout_tar";
671 # Validate pathout_tar as tar.
672 checkMakeTar
"$pathout_tar";
673 ## Add VERSION file if checkMakeTar had to create a tar (exited 1) or replace one (exited 2)
674 vbm
"exit status before magicWriteVersion:$?"
675 if [[ $?
-eq 1 ]] ||
[[ $?
-eq 2 ]]; then magicWriteVersion
; fi
676 } # Initialize tar, set pathout_tar
677 magicParseCompressionArg
() {
678 # Desc: Parses compression arguments specified by '-c' option
679 # Input: vars: optionCompress
680 # Output: cmd_compress, cmd_compress_suffix
681 # Depends: processArguments(), vbm(), checkapp(), gzip 1.9
682 if [[ "$optionCompress" = "true" ]]; then # Check if compression option active
683 if checkapp
gzip; then # Check if gzip available
684 cmd_compress
="gzip " && vbm
"cmd_compress:$cmd_compress";
685 cmd_compress_suffix
=".gz" && vbm
"cmd_compress_suffix:$cmd_compress_suffix";
687 yell
"ERROR:Compression enabled but \"gzip\" not found. Exiting."; exit 1;
690 cmd_compress
="tee /dev/null " && vbm
"cmd_compress:$cmd_compress";
691 cmd_compress_suffix
="" && vbm
"cmd_compress_suffix:$cmd_compress_suffix";
692 vbm
"DEBUG:Compression not enabled.";
694 } # Form compression cmd string and filename suffix
695 magicParseCustomTTL
() {
696 # Desc: Set user-specified TTLs for buffer and script
697 # Usage: magicParseCustomTTL
698 # Input: vars: argCustomBufferTTL (integer), argCustomScriptTTL_TE (string)
699 # Input: vars: optionCustomBufferTTL, optionCustomScriptTTL_TE
700 # Input: vars: bufferTTL (integer), scriptTTL_TE (string)
701 # Output: bufferTTL (integer), scriptTTL_TE (string)
702 # Depends: Bash 5.0.3, yell(), vbm(), validateInput(), showUsage()
704 # React to '-b, --buffer-ttl' option
705 if [[ "$optionCustomBufferTTL" = "true" ]]; then
706 ## T: Check if argCustomBufferTTL is an integer
707 if validateInput
"$argCustomBufferTTL" "integer"; then
708 ### T: argCustomBufferTTL is an integer
709 bufferTTL
="$argCustomBufferTTL" && vbm
"Custom bufferTTL from -b:$bufferTTL";
711 ### F: argcustomBufferTTL is not an integer
712 yell
"ERROR:Invalid integer argument for custom buffer time-to-live."; showUsage
; exit 1;
714 ## F: do not change bufferTTL
717 # React to '-B, --script-ttl' option
718 if [[ "$optionCustomScriptTTL_TE" = "true" ]]; then
719 ## T: Check if argCustomScriptTTL is a time element (ex: "day", "hour")
720 if validateInput
"$argCustomScriptTTL_TE" "time_element"; then
721 ### T: argCustomScriptTTL is a time element
722 scriptTTL_TE
="$argCustomScriptTTL_TE" && vbm
"Custom scriptTTL_TE from -B:$scriptTTL_TE";
724 ### F: argcustomScriptTTL is not a time element
725 yell
"ERROR:Invalid time element argument for custom script time-to-live."; showUsage
; exit 1;
727 ## F: do not change scriptTTL_TE
729 } # Sets custom script or buffer TTL if specified
731 # Desc: Parses -l option to set label
732 # In : optionLabel, argLabel
734 # Depends: Bash 5.0.3, vbm(), yell()
736 vbm
"STATUS:Started magicParseLabel() function.";
737 # Do nothing if optionLabel not set to true.
738 if [[ ! "$optionLabel" = "true" ]]; then
739 vbm
"STATUS:optionlabel not set to 'true'. Returning early.";
742 # Set label if optionLabel is true
743 if [[ "$optionLabel" = "true" ]]; then
744 label
="_""$argLabel";
745 vbm
"STATUS:Set label:$label";
747 vbm
"STATUS:Finished magicParseLabel() function.";
748 } # Set label used in output file name
749 magicParseProcessStrings
() {
750 # Desc: Processes user-supplied process strings into process commands for appendFileTar().
751 # Usage: magicParseProcessStrings
752 # In : vars: optionProcString optionNoStoreRaw optionStoreRaw argRawFileExt
753 # arry: argProcStrings, argProcFileExts
754 # Out: arry: procStrings, procFileExts
755 # Depends Bash 5.0.3, yell(), vbm()
758 vbm
"STATUS:Starting magicParseProcessStrings() function.";
760 ## Validate argRawFileExt
761 if [[ "$argRawFileExt" =~ ^
[.
][[:alnum
:]]*$
]]; then
762 rawFileExt
="$argRawFileExt";
765 # Add default stdin output file entries for procStrings, procFileExts
766 ## Check if user specified that no raw stdin be saved.
767 if [[ ! "$optionNoStoreRaw" = "true" ]]; then
768 ### T: --no-store-raw not set. Store raw. Append procStrings with cat.
769 #### Append procStrings array
770 procStrings
+=("cat ");
771 #### Check if --store-raw set.
772 if [[ "$optionStoreRaw" = "true" ]]; then
773 ##### T: --store-raw set. Append procFileExts with user-specified file ext
774 procFileExts
+=("$rawFileExt");
776 ##### F: --store-raw not set. Append procFileExts with default ".stdin" file ext
777 ###### Append procFileExts array
778 procFileExts
+=(".stdin");
781 ### F: --no-store-raw set. Do not store raw.
782 #### Do not append procStrings or procFileExts arrays.
786 # Do nothing more if optionProcString not set to true.
787 if [[ ! "$optionProcString" = "true" ]]; then
788 vbm
"STATUS:optionProcString not set to 'true'. Returning early.";
790 # Validate input array indices
791 ## Make sure that argProcStrings and argProcFileExts have same index counts
792 if ! [[ "${#argProcStrings[@]}" -eq "${#argProcFileExts[@]}" ]]; then
793 yell
"ERROR:Mismatch in number of elements in arrays argProcStrings and argProcFileExts:${#argProcStrings[@]} DNE ${#argProcFileExts[@]}";
794 yell
"argProcStrings:${argProcStrings[*]}"; yell
"argProcFileExts:${argProcFileExts[*]}"; exit 1; fi;
795 ## Make sure that no array elements are blank
796 for element
in "${argProcStrings[@]}"; do
797 if [[ -z "$element" ]]; then yell
"ERROR:Empty process string specified. Exiting."; exit 1; fi; done
798 for element
in "${argProcFileExts[@]}"; do
799 if [[ -z "$element" ]]; then yell
"ERROR:Empty output file extension specified. Exiting."; exit 1; fi; done
800 ## Make sure that no process string starts with '-' (ex: if only one arg supplied after '-p' option)
801 for element
in "${argProcStrings[@]}"; do
802 if [[ ! "$element" =~ ^
[-][[:print
:]]*$
]] && [[ "$element" =~ ^
[[:print
:]]*$
]]; then
803 yell
"ERROR:Illegal character '-' at start of process string element. Option syntax error?";
805 vbm
"STATUS:Quick check shows argProcStrings and argProcFileExts appear to have valid contents.";
806 procStrings
=("${argProcStrings[@]}"); # Export process command strings
807 procFileExts
=("${argProcFileExts[@]}"); # Export process command strings
808 vbm
"STATUS:Finished magicParseProcessStrings() function.";
809 } # Validate and save process strings and file extensions to arrays procStrings, procFileExts
810 magicParseRecipientArgs
() {
811 # Desc: Parses recipient arguments specified by '-r' option
812 # Input: vars: optionEncrypt, optionRecipients
813 # arry: argRecPubKeys from processArguments()
814 # Output: vars: cmd_encrypt, cmd_encrypt_suffix
815 # arry: recPubKeysValid, recPubKeysValidStatic
816 # Depends: processArguments(), yell(), vbm(), checkapp(), checkAgePubkey(), validateInput()
819 # Check if encryption option active.
820 if [[ "$optionEncrypt" = "true" ]] && [[ "$optionRecipients" = "true" ]]; then
821 if checkapp age
; then # Check that age is available.
822 for pubkey
in "${argRecPubKeys[@]}"; do # Validate recipient pubkey strings by forming test message
823 vbm
"DEBUG:Testing pubkey string:$pubkey";
824 if checkAgePubkey
"$pubkey" && \
825 ( validateInput
"$pubkey" "ssh_pubkey" || validateInput
"$pubkey" "age_pubkey"); then
826 #### Form age recipient string
827 recipients
="$recipients""-r '$pubkey' ";
828 vbm
"STATUS:Added pubkey for forming age recipient string:""$pubkey";
829 vbm
"DEBUG:recipients:""$recipients";
830 #### Add validated pubkey to recPubKeysValid array
831 recPubKeysValid
+=("$pubkey") && vbm
"DEBUG:recPubkeysValid:pubkey added:$pubkey";
833 yell
"ERROR:Exit code ""$?"". Invalid recipient pubkey string. Exiting."; exit 1;
836 vbm
"DEBUG:Finished processing argRecPubKeys array";
837 vbm
"STATUS:Array of validated pubkeys:${recPubKeysValid[*]}";
838 recPubKeysValidStatic
=("${recPubKeysValid[@]}"); # Save static image of pubkeys validated by this function
840 ## Form age command string
841 cmd_encrypt
="age ""$recipients " && vbm
"cmd_encrypt:$cmd_encrypt";
842 cmd_encrypt_suffix
=".age" && vbm
"cmd_encrypt_suffix:$cmd_encrypt_suffix";
844 yell
"ERROR:Encryption enabled but \"age\" not found. Exiting."; exit 1;
847 cmd_encrypt
="tee /dev/null " && vbm
"cmd_encrypt:$cmd_encrypt";
848 cmd_encrypt_suffix
="" && vbm
"cmd_encrypt_suffix:$cmd_encrypt_suffix";
849 vbm
"DEBUG:Encryption not enabled."
851 # Catch case if '-e' is set but '-r' or '-R' is not
852 if [[ "$optionEncrypt" = "true" ]] && [[ ! "$optionRecipients" = "true" ]]; then
853 yell
"ERROR:\\'-e\\' set but no \\'-r\\' or \\'-R\\' set."; exit 1; fi;
854 # Catch case if '-r' or '-R' set but '-e' is not
855 if [[ ! "$optionEncrypt" = "true" ]] && [[ "$optionRecipients" = "true" ]]; then
856 yell
"ERROR:\\'-r\\' or \\'-R\\' set but \\'-e\\' is not set."; exit 1; fi;
857 } # Populate recPubKeysValid with argRecPubKeys; form encryption cmd string and filename suffix
858 magicParseRecipientDir
() {
859 # Desc: Updates recPubKeysValid with pubkeys in dir specified by '-R' option ("recipient directory")
860 # Inputs: vars: optionEncrypt, optionRecDir, argRecDir,
861 # arry: recPubKeysValid
862 # Outputs: arry: recPubKeysValid
863 # Depends: processArguments(), yell(), vbm(), validateInput(), checkAgePubkey()
864 local recipientDir recFileLine updateRecipients
865 declare -a candRecPubKeysValid
867 # Check that '-e' and '-R' set
868 if [[ "$optionEncrypt" = "true" ]] && [[ "$optionRecDir" = "true" ]]; then
869 ### Check that argRecDir is a directory.
870 if [[ -d "$argRecDir" ]]; then
871 recipientDir
="$argRecDir" && vbm
"STATUS:Recipient watch directory detected:\"$recipientDir\"";
872 #### Initialize variable indicating outcome of pubkey review
873 unset updateRecipients
874 #### Add existing recipients
875 candRecPubKeysValid
=("${recPubKeysValidStatic[@]}");
876 #### Parse files in recipientDir
877 for file in "$recipientDir"/*; do
878 ##### Read first line of each file
879 recFileLine
="$(head -n1 "$file")" && vbm
"STATUS:Checking if pubkey:\"$recFileLine\"";
880 ##### check if first line is a valid pubkey
881 if checkAgePubkey
"$recFileLine" && \
882 ( validateInput
"$recFileLine" "ssh_pubkey" || validateInput
"$recFileLine" "age_pubkey"); then
883 ###### T: add candidate pubkey to candRecPubKeysValid
884 candRecPubKeysValid
+=("$recFileLine") && vbm
"STATUS:RecDir pubkey is valid pubkey:\"$recFileLine\"";
886 ###### F: throw warning;
887 yell
"ERROR:Invalid recipient file detected. Not modifying recipient list."
888 updateRecipients
="false";
891 #### Write updated recPubKeysValid array to recPubKeysValid if no failure detected
892 if ! [[ "$updateRecipients" = "false" ]]; then
893 recPubKeysValid
=("${candRecPubKeysValid[@]}") && vbm
"STATUS:Wrote candRecPubkeysValid to recPubKeysValid:\"${recPubKeysValid[*]}\"";
896 yell
"ERROR:$0:Recipient directory $argRecDir does not exist. Exiting."; exit 1;
899 # Handle case if '-R' set but '-e' not set
900 if [[ ! "$optionEncrypt" = "true" ]] && [[ "$optionRecDir" = "true" ]]; then
901 yell
"ERROR: \\'-R\\' is set but \\'-e\\' is not set."; fi;
902 } # Update recPubKeysValid with argRecDir
903 magicSetScriptTTL
() {
904 #Desc: Sets script_TTL seconds from provided time_element string argument
905 #Usage: magicSetScriptTTL [str time_element]
906 #Input: arg1: string (Ex: scriptTTL_TE; "day" or "hour")
907 #Output: var: scriptTTL (integer seconds)
908 #Depends: timeUntilNextHour, timeUntilNextDay
912 if [[ "$argTimeElement" = "day" ]]; then
913 # Set script lifespan to end at start of next day
914 if ! scriptTTL
="$(timeUntilNextDay)"; then # sets scriptTTL, then checks exit code
915 if [[ "$scriptTTL" -eq 0 ]]; then
916 ((scriptTTL
++)); # Add 1 because 0 would cause 'timeout' to never timeout.
918 yell
"ERROR: timeUntilNextDay exit code $?"; exit 1;
921 elif [[ "$argTimeElement" = "hour" ]]; then
922 # Set script lifespan to end at start of next hour
923 if ! scriptTTL
="$(timeUntilNextHour)"; then # sets scriptTTL, then checks exit code
924 if [[ "$scriptTTL" -eq 0 ]]; then
925 ((scriptTTL
++)); # Add 1 because 0 would cause 'timeout' to never timeout.
927 yell
"ERROR: timeUntilNextHour exit code $?"; exit 1;
931 yell
"ERROR:Invalid argument for setScriptTTL function:$argTimeElement"; exit 1;
933 } # Set scriptTTL in seconds until next (day|hour).
934 magicWriteVersion
() {
935 # Desc: Appends time-stamped VERSION to pathout_tar
936 # Usage: magicWriteVersion
937 # Input: vars: pathout_tar, dir_tmp
938 # Input: vars: scriptVersion, scriptURL, ageVersion, ageURL, scriptHostname
939 # Input: array: recPubKeysValid
940 # Output: appends tar (pathout_tar)
941 # Depends: bash 5.0.3, dateTimeShort(), appendArgTar()
942 local fileoutVersion contentVersion pubKeyIndex pubKeyIndex
944 # Set VERSION file name
945 fileoutVersion
="$(dateTimeShort)..VERSION";
947 # Gather VERSION data in contentVersion
948 contentVersion
="scriptVersion=$scriptVersion";
949 #contentVersion="$contentVersion""\\n";
950 contentVersion
="$contentVersion""\\n""scriptName=$scriptName";
951 contentVersion
="$contentVersion""\\n""scriptURL=$scriptURL";
952 contentVersion
="$contentVersion""\\n""ageVersion=$ageVersion";
953 contentVersion
="$contentVersion""\\n""ageURL=$ageURL";
954 contentVersion
="$contentVersion""\\n""date=$(date --iso-8601=seconds)";
955 contentVersion
="$contentVersion""\\n""hostname=$scriptHostname";
956 ## Add list of recipient pubkeys
957 for pubkey
in "${recPubKeysValid[@]}"; do
959 contentVersion
="$contentVersion""\\n""PUBKEY_$pubKeyIndex=$pubkey";
961 ## Process newline escapes
962 contentVersion
="$(echo -e "$contentVersion")"
964 # Write contentVersion as file fileoutVersion and write-append to pathout_tar
965 appendArgTar
"$contentVersion" "$fileoutVersion" "$pathout_tar" "$dir_tmp";
966 } # write version data to pathout_tar via appendArgTar()
967 magicProcessWriteBuffer
() {
968 # Desc: process and write buffer
969 # In : vars: bufferTTL bufferTTL_STR scriptHostname label dir_tmp SECONDS
971 # Out: file:(pathout_tar)
972 # Depends: Bash 5.0.3, date 8.30, yell(), vbm(), dateTimeShort(),
973 ### Note: These arrays should all have the same number of elements:
974 ### pathouts, fileouts, procFileExts, procStrings
976 local fn timeBufferStartLong timeBufferStart fileoutBasename
977 local -a fileouts pathouts
978 local writeCmd1 writeCmd2 writeCmd3 writeCmd4
980 vbm
"DEBUG:STATUS:$fn:Started magicProcessWriteBuffer().";
981 # Debug:Get function name
984 # Determine file paths (time is start of buffer period)
985 ## Calculate start time
986 timeBufferStartLong
="$(date --date="$bufferTTL seconds ago
" --iso-8601=seconds)" && \
987 vbm
"timeBufferStartLong:$timeBufferStartLong";
988 timeBufferStart
="$(dateTimeShort "$timeBufferStartLong" )" && \
989 vbm
"timeBufferStart:$timeBufferStart"; # Note start time YYYYmmddTHHMMSS+zzzz (no separators)
990 ## Set common basename
991 fileoutBasename
="$timeBufferStart""--""$bufferTTL_STR""..""$scriptHostname""$label" && \
992 vbm
"STATUS:Set fileoutBasename to:$fileoutBasename";
993 ## Determine output file name array
994 ### in: fileOutBasename cmd_compress_suffix cmd_encrypt_suffix procFileExts
995 for fileExt
in "${procFileExts[@]}"; do
996 fileouts
+=("$fileoutBasename""$fileExt""$cmd_compress_suffix""$cmd_encrypt_suffix") && \
997 vbm
"STATUS:Added $fileExt to fileouts:${fileouts[*]}";
999 for fileName
in "${fileouts[@]}"; do
1000 pathouts
+=("$dir_tmp"/"$fileName") && \
1001 vbm
"STATUS:Added $fileName to pathouts:${pathouts[*]}";
1003 ## Update pathout_tar
1006 # Process and write buffers to dir_tmp
1007 ## Prepare command strings
1008 writeCmd1
="printf \"%s\\\\n\" \"\${buffer[@]}\""; # printf "%s\\n" "${buffer[@]}"
1009 #writeCmd2="" # NOTE: Specified by parsing array procStrings
1010 writeCmd3
="$cmd_compress";
1011 writeCmd4
="$cmd_encrypt";
1013 ## Process buffer and write to dir_tmp
1014 for index
in "${!pathouts[@]}"; do
1015 writeCmd2
="${procStrings[$index]}"
1016 eval "$writeCmd1 | $writeCmd2 | $writeCmd3 | $writeCmd4" >> "${pathouts[$index]}";
1019 # Append dir_tmp files to pathout_tar
1020 wait; # Wait to avoid collision with older magicProcessWriteBuffer() instances (see https://www.tldp.org/LDP/abs/html/x9644.html )
1021 for index
in "${!pathouts[@]}"; do
1022 appendFileTar
"${pathouts[$index]}" "${fileouts[$index]}" "$pathout_tar" "$dir_tmp";
1025 # Remove secured chunks from dir_tmp
1026 for path
in "${pathouts[@]}"; do
1030 vbm
"DEBUG:STATUS:$fn:Finished magicProcessWriteBuffer().";
1031 } # Process and Write buffer
1035 processArguments
"$@";
1036 ## Determine working directory
1037 magicInitWorkingDir
; # Sets dir_tmp from argTempDirPriority
1038 ## Set output encryption and compression option strings
1039 ### React to "-e" and "-r" ("encryption recipients") options
1040 magicParseRecipientArgs
; # Updates recPubKeysValid, cmd_encrypt[_suffix] from argRecPubKeys
1041 ### React to "-R" ("recipient directory") option
1042 magicParseRecipientDir
; # Updates recPubKeysValid
1043 ### React to "-c" ("compression") option
1044 magicParseCompressionArg
; # Updates cmd_compress[_suffix]
1045 ## React to "-b" and "-B" (custom buffer and script TTL) options
1046 magicParseCustomTTL
; # Sets custom scriptTTL_TE and/or bufferTTL if specified
1047 ## React to "-p" (user-supplied process command and file extension strings) options
1048 magicParseProcessStrings
; # Sets arrays: procStrings, procFileExts
1049 ## React to "-l" (output file label) option
1050 magicParseLabel
; # sets label (ex: "_location")
1051 ## React to "-w" (how to name raw stdin file) option
1052 magicParseStoreRaw
; # sets raw_suffix
1054 # Perform secondary setup operations
1055 ## Set script lifespan (scriptTTL from scriptTTL_TE)
1056 magicSetScriptTTL
"$scriptTTL_TE";
1057 ## File name substring (ISO-8601 duration from bufferTTL)
1058 bufferTTL_STR
="$(timeDuration "$bufferTTL")" && vbm
"DEBUG:bufferTTL_STR:$bufferTTL_STR";
1059 ## Init temp working dir
1060 try mkdir
"$dir_tmp" && vbm
"DEBUG:Working dir created at dir_tmp:$dir_tmp";
1061 ## Initialize output tar (set pathout_tar)
1064 # Check vital apps, files, dirs
1065 if ! checkapp
tar && ! checkdir
"$dirOut" "dir_tmp"; then
1066 yell
"ERROR:Critical components missing.";
1067 displayMissing
; yell
"Exiting."; exit 1; fi
1069 # MAIN LOOP: Run until script TTL seconds pass
1071 while [[ $SECONDS -lt "scriptTTL" ]]; do
1072 bufferTOD
="$((SECONDS + bufferTTL))"; # Set buffer round time-of-death
1073 lineCount
=0; # Debug counter
1074 # Consume stdin to fill buffer until buffer time-of-death (TOD) arrives
1075 while read -r -t "$bufferTTL" line
&& [[ $SECONDS -lt "$bufferTOD" ]]; do
1076 # Append line to buffer array
1078 echo "DEBUG:Processing line:$lineCount";
1079 echo "DEBUG:Current line :$line";
1080 echo "DEBUG:buf elem count :${#buffer[@]}";
1083 # Create dir_tmp if missing
1084 if ! [[ -d "$dir_tmp" ]]; then yell
"ERROR:dir_tmp existence failure:$dir_tmp"; try mkdir
"$dir_tmp" && vbm
"DEBUG:Working dir recreated dir_tmp:$dir_tmp"; fi
1085 # Update encryption recipient array
1086 magicParseRecipientDir
; # Update recPubKeysValid with argRecDir
1087 # Export buffer to asynchronous processing.
1088 magicProcessWriteBuffer
&
1089 unset buffer
; # Clear buffer array for next bufferRound
1090 # Increment buffer round
1096 try
rm -r "$dir_tmp" && vbm
"Removed dir_tmp:$dir_tmp";
1098 vbm
"STATUS:Main function finished.";
1101 #===END Declare local script functions===
1102 #==END Define script parameters==
1104 #==BEGIN Perform work and exit==
1105 main
"$@" # Run main function.
1107 #==END Perform work and exit==
1109 # Author: Steven Baltakatei Sandoval;