chore(unitproc):checkMakeTar:Add author, license
[BK-2020-03.git] / unitproc / bktemp-checkMakeTar
1 #!/bin/bash
2
3 # Desc: Checks that a valid tar archive exists, creates one otherwise
4
5
6 yell() { echo "$0: $*" >&2; } #o Yell, Die, Try Three-Fingered Claw technique
7 die() { yell "$*"; exit 111; } #o Ref/Attrib: https://stackoverflow.com/a/25515370
8 try() { "$@" || die "cannot $*"; } #o
9
10 #===BEGIN Declare local script functions===
11 checkMakeTar() {
12 # Desc: Checks that a valid tar archive exists, creates one otherwise
13 # Usage: checkMakeTar [ path ]
14 # Version: 1.0.0
15 # Input: arg1: path of tar archive
16 # Output: exit code 0 : tar readable
17 # exit code 1 : tar missing; created
18 # exit code 2 : tar not readable; moved; replaced
19 # Depends: try, tar, date
20 local PATH_TAR returnFlag0 returnFlag1 returnFlag2
21 PATH_TAR="$1"
22
23 # Check if file is a valid tar archive
24 if tar --list --file="$PATH_TAR" 1>/dev/null 2>&1; then
25 ## T1: return success
26 returnFlag0="tar valid";
27 else
28 ## F1: Check if file exists
29 if [[ -f "$PATH_TAR" ]]; then
30 ### T: Rename file
31 try mv "$PATH_TAR" "$PATH_TAR""--broken--""$(date +%Y%m%dT%H%M%S)" && \
32 returnFlag1="tar moved";
33 else
34 ### F: -
35 :
36 fi
37 ## F2: Create tar archive, return 0
38 try tar --create --file="$PATH_TAR" --files-from=/dev/null && \
39 returnFlag2="tar created";
40 fi
41
42 # Determine function return code
43 if [[ "$returnFlag0" = "tar valid" ]]; then
44 return 0;
45 elif [[ "$returnFlag2" = "tar created" ]] && ! [[ "$returnFlag1" = "tar moved" ]]; then
46 return 1; # tar missing so created
47 elif [[ "$returnFlag2" = "tar created" ]] && [[ "$returnFlag1" = "tar moved" ]]; then
48 return 2; # tar not readable so moved; replaced
49 fi
50 } # checks if arg1 is tar; creates one otherwise
51 #===END Declare local script functions===
52
53 #====BEGIN sample code====
54 #myFile="/tmp/$(date +%s)..tar"
55 myFile="/tmp/$(date +%Y%m%d).tar"
56 if [[ -f "$myFile" ]]; then yell "$myFile already exists."; else yell "$myFile doesn't yet exist."; fi
57 if checkMakeTar "$myFile"; then
58 yell "checkMakeTar() function run and exited:$?";
59 else
60 yell "checkMakeTar() function run and exited:$?";
61 fi
62
63 if [[ -f "$myFile" ]]; then
64 yell "Now exists :$myFile";
65 ls -l "$myFile";
66 else
67 yell "Does not exist:$myFile";
68 ls -l "$myFile";
69 fi
70 #====END sample code====
71
72 # Author: Steven Baltakatei Sandoval
73 # License: GPLv3+