feat(bkgpslog):Add encryption option
[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 PATH="/opt/bktei:$PATH" # Add default baltakatei script install directory to PATH (necessary for other bk scripts)
9 SCRIPT_HOSTNAME=$(hostname) # Save hostname of system running this script.
10 SCRIPT_VERSION="bkgpslog 0.0.1" # Define version of script.
11 SCRIPT_TIME_SHORT="$(date +%Y%m%dT%H%M%S%z)" # Save current date & time in ISO-8601 format.
12 SCRIPT_DATE_SHORT="$(date +%Y%m%d)" # Save current date in ISO-8601 format.
13
14 declare -Ag appRollCall # Associative array for storing app status
15 declare -Ag fileRollCall # Associative array for storing file status
16 declare -Ag dirRollCall # Associative array for storing dir status
17 declare -a recPubKeys # for processArguments function
18
19 #===BEGIN Declare local script functions===
20 checkapp() {
21 # Desc: If arg is a command, save result in assoc array 'appRollCall'
22 # Usage: checkapp arg1 arg2 arg3 ...
23 # Input: global assoc. array 'appRollCall'
24 # Output: adds/updates key(value) to global assoc array 'appRollCall'
25 local returnState
26 #echo "DEBUG:$(date +%S.%N)..Starting checkapp function."
27 #echo "DEBUG:args: $@"
28 #echo "DEBUG:returnState:$returnState"
29
30 #===Process Args===
31 for arg in "$@"; do
32 #echo "DEBUG:processing arg:$arg"
33 if command -v "$arg" 1>/dev/null 2>&1; then # Check if arg is a valid command
34 appRollCall[$arg]="true";
35 #echo "DEBUG:appRollCall[$arg]:"${appRollCall[$arg]}
36 if ! [ "$returnState" = "false" ]; then returnState="true"; fi
37 else
38 appRollCall[$arg]="false"; returnState="false";
39 fi
40 done
41
42 #for key in "${!appRollCall[@]}"; do echo "DEBUG:$key => ${appRollCall[$key]}"; done
43 #echo "DEBUG:evaluating returnstate. returnState:"$returnState
44
45 #===Determine function return code===
46 if [ "$returnState" = "true" ]; then
47 #echo "DEBUG:checkapp returns true for $arg";
48 return 0;
49 else
50 #echo "DEBUG:checkapp returns false for $arg";
51 return 1;
52 fi
53 } # Check that app exists
54 checkfile() {
55 # Desc: If arg is a file path, save result in assoc array 'fileRollCall'
56 # Usage: checkfile arg1 arg2 arg3 ...
57 # Input: global assoc. array 'fileRollCall'
58 # Output: adds/updates key(value) to global assoc array 'fileRollCall';
59 # Output: returns 0 if app found, 1 otherwise
60 local returnState
61
62 #===Process Args===
63 for arg in "$@"; do
64 #echo "DEBUG:processing arg:$arg"
65 if [ -f "$arg" ]; then
66 fileRollCall["$arg"]="true";
67 #echo "DEBUG:fileRollCall[\"$arg\"]:"${fileRollCall["$arg"]}
68 if ! [ "$returnState" = "false" ]; then returnState="true"; fi
69 else
70 fileRollCall["$arg"]="false"; returnState="false";
71 fi
72 done
73
74 #for key in "${!fileRollCall[@]}"; do echo "DEBUG:fileRollCall key [$key] is:${fileRollCall[$key]}"; done
75 #echo "DEBUG:evaluating returnstate. returnState:"$returnState
76
77 #===Determine function return code===
78 if [ "$returnState" = "true" ]; then
79 #echo "DEBUG:checkapp returns true for $arg";
80 return 0;
81 else
82 #echo "DEBUG:checkapp returns false for $arg";
83 return 1;
84 fi
85 } # Check that file exists
86 checkdir() {
87 # Desc: If arg is a dir path, save result in assoc array 'dirRollCall'
88 # Usage: checkdir arg1 arg2 arg3 ...
89 # Input: global assoc. array 'dirRollCall'
90 # Output: adds/updates key(value) to global assoc array 'dirRollCall';
91 # Output: returns 0 if app found, 1 otherwise
92 local returnState
93
94 #===Process Args===
95 for arg in "$@"; do
96 #echo "DEBUG:processing arg:$arg"
97 if [ -d "$arg" ]; then
98 dirRollCall["$arg"]="true";
99 #echo "DEBUG:dirRollCall[\"$arg\"]:"${dirRollCall["$arg"]}
100 if ! [ "$returnState" = "false" ]; then returnState="true"; fi
101 elif [ "$arg" = "" ]; then
102 dirRollCall["$arg"]="false"; returnState="false";
103 else
104 returnState="false";
105 fi
106 done
107
108 #for key in "${!dirRollCall[@]}"; do echo "DEBUG:dirRollCall key [$key] is:${dirRollCall[$key]}"; done
109 #echo "DEBUG:evaluating returnstate. returnState:"$returnState
110
111 #===Determine function return code===
112 if [ "$returnState" = "true" ]; then
113 #echo "DEBUG:checkapp returns true for $arg";
114 return 0;
115 else
116 #echo "DEBUG:checkapp returns false for $arg";
117 return 1;
118 fi
119 } # Check that dir exists
120
121 # Yell, Die, Try Three-Fingered Claw technique
122 # Ref/Attrib: https://stackoverflow.com/a/25515370
123 yell() { echo "$0: $*" >&2; }
124 die() { yell "$*"; exit 111; }
125 try() { "$@" || die "cannot $*"; }
126
127 echoerr() {
128 echo "$@" 1>&2; # Define stderr echo function.
129 } # Define stderr message function.
130 showUsage() {
131 echoerr "USAGE:"
132 echoerr " bkgpslog [ options ]"
133 echoerr
134 echoerr "OPTIONS:"
135 echoerr " -h, --help"
136 echoerr " Display help information."
137 echoerr
138 echoerr " --version"
139 echoerr " Display script version."
140 echoerr
141 echoerr " -v, --verbose"
142 echoerr " Display debugging info."
143 echoerr
144 echoerr " -e, --encrypt"
145 echoerr " Encrypt output."
146 echoerr
147 echoerr " -r, --recipient [ pubkey string ]"
148 echoerr " Specify recipient."
149 echoerr
150 echoerr " -o, --output [ directory ]"
151 echoerr " Specify output directory to save logs."
152 echoerr
153 echoerr "EXAMPLE: (bash script lines)"
154 echoerr "/bin/bash bkgpslog -e \\"
155 echoerr "-r age1mrmfnwhtlprn4jquex0ukmwcm7y2nxlphuzgsgv8ew2k9mewy3rs8u7su5 \\"
156 echoerr "-r age1ala848kqrvxc88rzaauc6vc5v0fqrvef9dxyk79m0vjea3hagclswu0lgq \\"
157 echoerr "-o ~/Sync/Location"
158 } # Display information on how to use this script.
159 showVersion() {
160 echoerr "$SCRIPT_VERSION"
161 } # Display script version.
162 vbm() {
163 # Usage: vbm "DEBUG:verbose message here"
164 # Description: Prints verbose message ("vbm") to stderr if OPTION_VERBOSE is set to "true".
165 # Input:
166 # - OPTION_VERBOSE variable set by processArguments function. (ex: "true", "false")
167 # - "$@" positional arguments fed to this function.
168 # Output: stderr
169 # Script function dependencies: echoerr
170 # External function dependencies: echo
171 # Last modified: 2020-04-11T23:57Z
172 # Last modified by: Steven Baltakatei Sandoval
173 # License: GPLv3+
174 # Ref./Attrib:
175
176 if [ "$OPTION_VERBOSE" = "true" ]; then
177 FUNCTION_TIME=$(date --iso-8601=ns); # Save current time in nano seconds.
178 echoerr "[$FUNCTION_TIME] ""$*"; # Display argument text.
179 fi
180
181 # End function
182 return 0; # Function finished.
183 } # Verbose message display function.
184 processArguments() {
185 while [ ! $# -eq 0 ]; do # While number of arguments ($#) is not (!) equal to (-eq) zero (0).
186 #echoerr "DEBUG:Starting processArguments while loop."
187 #echoerr "DEBUG:Provided arguments are:""$*"
188 case "$1" in
189 -h | --help) showUsage; exit 1;; # Display usage.
190 --version) showVersion; exit 1;; # Show version
191 -v | --verbose) OPTION_VERBOSE="true"; vbm "DEBUG:Verbose mode enabled.";; # Enable verbose mode.
192 -o | --output) if [ -d "$2" ]; then DIROUT="$2"; vbm "DEBUG:DIROUT:$DIROUT"; shift; fi ;; # Define output directory.
193 -e | --encrypt) OPTION_ENCRYPT="true"; vbm "DEBUG:Encrypted output mode enabled.";;
194 -r | --recipient) # Add 'age' recipient via public key string
195 recPubKeys+=("$2"); shift;;
196 *) echoerr "ERROR: Unrecognized argument."; exit 1;; # Handle unrecognized options.
197 esac
198 shift
199 done
200 } # Argument Processing
201 timeUntilNextDay(){
202 # Desc: Report seconds until next day.
203 # Output: stdout: integer seconds until next day
204 # Output: exit code 0 if stdout > 0; 1 if stdout = 0; 2 if stdout < 0
205 # Usage: timeUntilNextDay
206 # Usage: if ! myTTL="$(timeUntilNextDay)"; then yell "ERROR in if statement"; exit 1; fi
207 local returnState TIME_CURRENT TIME_NEXT_DAY SECONDS_UNTIL_NEXT_DAY
208 TIME_CURRENT="$(date --iso-8601=seconds)" ; # Produce `date`-parsable current timestamp with resolution of 1 second.
209 TIME_NEXT_DAY="$(date -d "$TIME_CURRENT next day" --iso-8601=date)"; # Produce timestamp of beginning of tomorrow with resolution of 1 second.
210 SECONDS_UNTIL_NEXT_DAY="$(( $(date +%s -d "$TIME_NEXT_DAY") - $(date +%s -d "$TIME_CURRENT") ))" ; # Calculate seconds until closest future midnight (res. 1 second).
211 if [[ "$SECONDS_UNTIL_NEXT_DAY" -gt 0 ]]; then
212 returnState="true";
213 elif [[ "$SECONDS_UNTIL_NEXT_DAY" -eq 0 ]]; then
214 returnState="WARNING_ZERO";
215 yell "WARNING:Reported time until next day exactly zero.";
216 elif [[ "$SECONDS_UNTIL_NEXT_DAY" -lt 0 ]]; then
217 returnState="WARNING_NEGATIVE";
218 yell "WARNING:Reported time until next day is negative.";
219 fi
220
221 try echo "$SECONDS_UNTIL_NEXT_DAY"; # Report
222
223 #===Determine function return code===
224 if [[ "$returnState" = "true" ]]; then
225 return 0;
226 elif [[ "$returnState" = "WARNING_ZERO" ]]; then
227 return 1;
228 elif [[ "$returnState" = "WARNING_NEGATIVE" ]]; then
229 return 2;
230 fi
231 } # Report seconds until next day
232 timeUntilNextHour(){
233 # Desc: Report seconds until next hour
234 # Output: stdout: integer seconds until next hour
235 # Output: exit code 0 if stdout > 0; 1 if stdout = 0; 2 if stdout < 0
236 # Usage: timeUntilNextHour
237 # Usage: if ! myTTL="$(timeUntilNextHour)"; then yell "ERROR in if statement"; exit 1; fi
238 local returnState TIME_CURRENT TIME_NEXT_HOUR SECONDS_UNTIL_NEXT_HOUR
239 TIME_CURRENT="$(date --iso-8601=seconds)"; # Produce `date`-parsable current timestamp with resolution of 1 second.
240 TIME_NEXT_HOUR="$(date -d "$TIME_CURRENT next hour" --iso-8601=hours)"; # Produce `date`-parsable current time stamp with resolution of 1 second.
241 SECONDS_UNTIL_NEXT_HOUR="$(( $(date +%s -d "$TIME_NEXT_HOUR") - $(date +%s -d "$TIME_CURRENT") ))"; # Calculate seconds until next hour (res. 1 second).
242 if [[ "$SECONDS_UNTIL_NEXT_HOUR" -gt 0 ]]; then
243 returnState="true";
244 elif [[ "$SECONDS_UNTIL_NEXT_HOUR" -eq 0 ]]; then
245 returnState="WARNING_ZERO";
246 yell "WARNING:Reported time until next hour exactly zero.";
247 elif [[ "$SECONDS_UNTIL_NEXT_HOUR" -lt 0 ]]; then
248 returnState="WARNING_NEGATIVE";
249 yell "WARNING:Reported time until next hour is negative.";
250 fi
251
252 try echo "$SECONDS_UNTIL_NEXT_HOUR"; # Report
253
254 #===Determine function return code===
255 if [[ "$returnState" = "true" ]]; then
256 return 0;
257 elif [[ "$returnState" = "WARNING_ZERO" ]]; then
258 return 1;
259 elif [[ "$returnState" = "WARNING_NEGATIVE" ]]; then
260 return 2;
261 fi
262 } # Report seconds until next hour
263 dateTimeShort(){
264 # Desc: Timestamp without separators (YYYYmmddTHHMMSS+zzzz)
265 # Usage: dateTimeShort
266 # Output: stdout: timestamp (ISO-8601, no separators)
267 local TIME_CURRENT TIME_CURRENT_SHORT
268 TIME_CURRENT="$(date --iso-8601=seconds)" ; # Produce `date`-parsable current timestamp with resolution of 1 second.
269 TIME_CURRENT_SHORT="$(date -d "$TIME_CURRENT" +%Y%m%dT%H%M%S%z)"; # Produce separator-less current timestamp with resolution 1 second.
270 echo "$TIME_CURRENT_SHORT";
271 } # Get date&time without separators
272 main() {
273 processArguments "$@" # Process arguments.
274 if [[ "$OPTION_ENCRYPT" = "true" ]]; then # Check if encryption option active.
275 if checkapp age; then # Check that age is available.
276 for pubkey in "${recPubKeys[@]}"; do # Validate recipient pubkey strings by forming test message
277 vbm "DEBUG:Testing pubkey string:$pubkey"
278 if ! echo "butts" | age -a -r "$pubkey" 1>/dev/null; then
279 yell "ERROR:Exit code ""$?"". Invalid recipient pubkey string. Exiting."; exit 1; fi
280 done
281 else
282 yell "ERROR:Encryption enabled but \"age\" not found. Exiting."; exit 1;
283 fi
284 fi
285
286 if checkapp gpspipe && checkdir "$DIROUT"; then
287
288 # # Set script lifespan to end at start of next day
289 # if ! scriptTTL="$(timeUntilNextDay)"; then
290 # if [[ "$scriptTTL" -eq 0 ]]; then
291 # ((scriptTTL++)); # Add 1 because 0 would cause 'timeout' to never timeout.
292 # else
293 # yell "ERROR: timeUntilNextDay exit code $?"; exit 1;
294 # fi;
295 # fi;
296
297 # Set script lifespan to end at start of next hour
298 if ! scriptTTL="$(timeUntilNextHour)"; then
299 if [[ "$scriptTTL" -eq 0 ]]; then
300 ((scriptTTL++)); # Add 1 because 0 would cause 'timeout' to never timeout.
301 else
302 yell "ERROR: timeUntilNextHour exit code $?"; exit 1;
303 fi;
304 fi;
305
306 # Determine buffer lifespan
307 bufferTTL="60";
308
309 # Record gps data until script lifespan ends
310 declare debugCounter; debugCounter="0"
311 while [[ "$SECONDS" -lt "$scriptTTL" ]]; do
312 ((debugCounter++))
313 # Determine output file paths (time is start of buffer period)
314 FILEOUT_BASENAME="$(dateTimeShort)""--P""$bufferTTL""S..""$SCRIPT_HOSTNAME""_location" ; # ISO-8601 YYYYmmddTHHMMSS+zzP[$bufferTTL]S
315 FILEOUT_NMEA="$FILEOUT_BASENAME".nmea ;
316 FILEOUT_GPX="$FILEOUT_BASENAME".gpx ;
317 FILEOUT_KML="$FILEOUT_BASENAME".kml ;
318 # Fill buffer
319 buffer="$(timeout "$bufferTTL""s" gpspipe -r)"; # Record gpspipe nmea data to buffer for bufferTTL seconds
320 # Process and save buffers
321 echo "$buffer" > "$DIROUT"/"$FILEOUT_NMEA" & # Save NMEA format
322 echo "$buffer" | gpsbabel -i nmea -f - -o gpx -F - > "$DIROUT"/"$FILEOUT_GPX" & # Save GPX format
323 echo "$buffer" | gpsbabel -i nmea -f - -o kml -F - > "$DIROUT"/"$FILEOUT_KML" & # Save KML format
324 vbm "DEBUG:Completed buffer session $debugCounter ." 1>&2;
325 # Reset buffer and filenames
326 unset buffer FILEOUT_BASENAME FILEOUT_NMEA FILEOUT_GPX FILEOUT_KML;
327 done
328 fi
329 } # Main function.
330 #===END Declare local script functions===
331 #==END Define script parameters==
332
333
334 #==BEGIN Perform work and exit==
335 main "$@" # Run main function.
336 exit 0;
337 #==END Perform work and exit==
338
339
340
341 #gpspipe -r -d -l -o "$DIROUT1"/"$FILEOUT1" ;