feat(unitproc):Add setTimeZoneEV function
[BK-2020-03.git] / unitproc / bktemp-setTimeZoneEV
1 #!/bin/bash
2
3 # Desc: Set time zone environment variable TZ
4
5 yell() { echo "$0: $*" >&2; } # Yell, Die, Try Three-Fingered Claw technique; # Ref/Attrib: https://stackoverflow.com/a/25515370
6 die() { yell "$*"; exit 111; }
7 try() { "$@" || die "cannot $*"; }
8 setTimeZoneEV(){
9 # Desc: Set time zone environment variable TZ
10 # Usage: setTimeZoneEV arg1
11 # Input: arg1: 'date'-compatible timezone string (ex: "America/New_York")
12 # TZDIR env var (optional; default: "/usr/share/zoneinfo")
13 # Output: exports TZ
14 # exit code 0 on success
15 # exit code 1 on incorrect number of arguments
16 # exit code 2 if unable to validate arg1
17 # Depends: yell, die, try
18 ARG1="$1"
19 local tzDir returnState
20 if ! [[ $# -eq 1 ]]; then
21 yell "ERROR:Invalid argument count.";
22 return 1;
23 fi
24
25 # Read TZDIR env var if available
26 if printenv TZDIR 1>/dev/null 2>&1; then
27 tzDir="$(printenv TZDIR)";
28 else
29 tzDir="/usr/share/zoneinfo";
30 fi
31
32 # Validate TZ string
33 if ! [[ -f "$tzDir"/"$ARG1" ]]; then
34 yell "ERROR:Invalid time zone argument.";
35 return 2;
36 else
37 # Export ARG1 as TZ environment variable
38 TZ="$ARG1" && export TZ && returnState="true";
39 fi
40
41 # Determine function return code
42 if [ "$returnState" = "true" ]; then
43 return 0;
44 fi
45 } # Exports TZ environment variable
46
47 #==BEGIN sample code==
48 date --iso-8601=seconds; echo "==============="; sleep 2
49
50 date --iso-8601=seconds
51 cmd1="setTimeZoneEV America/New_York"
52 echo "Running:$cmd1"; $cmd1; echo "Exit code:$?"
53 date --iso-8601=seconds; echo "==============="; sleep 2
54
55 date --iso-8601=seconds
56 cmd2="setTimeZoneEV Asia/Tokyo"
57 echo "Running:$cmd2"; $cmd2; echo "Exit code:$?"
58 date --iso-8601=seconds; echo "==============="; sleep 2
59
60 date --iso-8601=seconds
61 cmd3="setTimeZoneEV";
62 echo "Running:$cmd3"; $cmd3; echo "Exit code:$?"
63 date --iso-8601=seconds; echo "==============="; sleep 2
64
65 date --iso-8601=seconds
66 cmd4="setTimeZoneEV Pacific/Lemuria"
67 echo "Running:$cmd4"; $cmd4; echo "Exit code:$?"
68 date --iso-8601=seconds; echo "==============="; sleep 2
69 #==END sample code==
70
71 # Author: Steven Baltakatei Sandoval
72 # License: GPLv3+
73
74