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