-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.sh
733 lines (606 loc) · 12.9 KB
/
lib.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
#!/bin/bash
# ###########################
# Bash Shell Function Library
# ###########################
#
# Author: Zoran Olujic <[email protected]>
# Contributions by: Jani Hurskainen
#
# Do not edit this file. Just source it into your script
# and override the variables to change their value.
#
init () {
#
# Debug mode shows more verbose output to screen and log files.
# Value: yes or no (y / n)
#
DEBUG=no
#
# Syslog style log messages
#
if ! defined LOGDATEFORMAT
then
LOGDATEFORMAT="%b %e %H:%M:%S"
fi
if ! defined LOG_FILE
then
LOG_FILE=$0.log
fi
#
# Enable / disable logging to a file
# Value: yes or no (y / n)
#
if ! defined LOG_ENABLED
then
LOG_ENABLED=no
fi
if ! defined SYSLOG_ENABLED
then
SYSLOG_ENABLED=no
fi
if ! defined SYSLOG_TAG
then
SYSLOG_TAG=$0
fi
#
# Use colours in output.
#
RED="tput setaf 1"
GREEN="tput setaf 2"
YELLOW="tput setaf 3"
BLUE="tput setaf 4"
MAGENTA="tput setaf 5"
CYAN="tput setaf 6"
LIGHT_BLUE="$CYAN"
BOLD="tput bold"
DEFAULT="tput sgr0"
RED_BG="tput setab 1"
GREEN_BG="tput setab 2"
YELLOW_BG="tput setab 3"
BLUE_BG="tput setab 4"
MAGENTA_BG="tput setab 5"
CYAN_BG="tput setab 6"
info () {
echo -e "$($BOLD)$1$($DEFAULT)"
}
pass () {
echo -e "$($BOLD)$($BLUE)\n$1$($DEFAULT)"
}
warn () {
echo -e "$($BOLD)$($RED)$1$($DEFAULT)"
}
#
# Bug fix for Bash, parsing exclamation mark.
#
set +o histexpand
#
# returns 0 if a variable is defined (set)
# returns 1 if a variable is unset
#
}
function defined {
[[ ${!1-X} == ${!1-Y} ]]
}
#
# returns 0 if a variable is defined (set) and value's length > 0
# returns 1 otherwise
#
function has_value {
if defined $1; then
if [[ -n ${!1} ]]; then
return 0
fi
fi
return 1
}
#
# returns 0 if a directory exists
# returns 1 otherwise
#
function directory_exists {
if [[ -d "$1" ]]; then
return 0
fi
return 1
}
#
# returns 0 if a (regular) file exists
# returns 1 otherwise
#
function file_exists {
if [[ -f "$1" ]]; then
return 0
fi
return 1
}
#
# returns lowercase string
#
function tolower {
echo "$1" | tr '[:upper:]' '[:lower:]'
}
#
# returns uppercase string
#
function toupper {
echo "$1" | tr '[:lower:]' '[:upper:]'
}
#
# Only returns the first part of a string, delimited by tabs or spaces
#
function trim {
echo $1
}
#
# Dummy function to provide usage instructions.
# Override this function if required.
#
show_usage () {
MESSAGE="$1"
echo "$MESSAGE"
exit 1
}
#
# Checks if a variable is set to "y" or "yes".
# Usefull for detecting if a configurable option is set or not.
#
option_enabled () {
VAR="$1"
VAR_VALUE=$(eval echo \$$VAR)
if [[ "$VAR_VALUE" == "y" ]] || [[ "$VAR_VALUE" == "yes" ]]
then
return 0
else
return 1
fi
}
#
# The log funcion just puts a string into a file, prepended with a date & time in
# syslog format.
#
log2syslog () {
if option_enabled SYSLOG_ENABLED
then
MESSAGE="$1"
logger -t "$SYSLOG_TAG" " $MESSAGE" #The space is not a typo!"
fi
}
#
# This function writes messages to a log file and/or syslog
# The only argument is a message that has to be logged.
#
log () {
if option_enabled LOG_ENABLED || option_enabled SYSLOG_ENABLED
then
LOG_MESSAGE="$1"
DATE=`date +"$LOGDATEFORMAT"`
if has_value LOG_MESSAGE
then
LOG_STRING="$DATE $LOG_MESSAGE"
else
LOG_STRING="$DATE -- empty log message, no input received --"
fi
if option_enabled LOG_ENABLED
then
echo "$LOG_STRING" >> "$LOG_FILE"
fi
if option_enabled SYSLOG_ENABLED
then
#
# Syslog already prepends a date/time stamp so only the message
# is logged.
#
log2syslog "$LOG_MESSAGE"
fi
fi
}
#
# This function basically replaces the 'echo' function in bash scripts.
# The added functionality over echo is logging and using colors.
#
# The first argument is the string / message that must be displayed.
# The second argument is the text color.
msg () {
MESSAGE="$1"
COLOR="$2"
if ! has_value COLOR
then
COLOR="$DEFAULT"
fi
if has_value "MESSAGE"
then
$COLOR
echo "$MESSAGE"
$DEFAULT
log "$MESSAGE"
else
echo "-- no message received --"
log "$MESSAGE"
fi
}
#
# This function echos a message
# and displays the status at the end of the line.
#
# It can be used to create status messages other
# than the default messages available such as
# OK or FAIL
#
msg_status () {
MESSAGE="$1"
STATUS="$2"
status_color "$STATUS"
msg "$MESSAGE" "$COLOR"
display_status "$STATUS"
}
#
# These functions are just short hand for messages like
# msg_status "this message is ok" OK
#
#
# The following functions are shorthand for
# msg_status "a message" OK
# msg_status "another message" FAIL
msg_emergency () {
MESSAGE="$1"
STATUS="EMERGENCY"
msg_status "$MESSAGE" "$STATUS"
}
msg_alert () {
MESSAGE="$1"
STATUS="ALERT"
msg_status "$MESSAGE" "$STATUS"
}
msg_critical () {
MESSAGE="$1"
STATUS="CRITICAL"
msg_status "$MESSAGE" "$STATUS"
}
msg_error () {
MESSAGE="$1"
STATUS="ERROR"
msg_status "$MESSAGE" "$STATUS"
}
msg_warning () {
MESSAGE="$1"
STATUS="WARNING"
msg_status "$MESSAGE" "$STATUS"
}
msg_notice () {
MESSAGE="$1"
STATUS="NOTICE"
msg_status "$MESSAGE" "$STATUS"
}
msg_info () {
MESSAGE="$1"
STATUS="INFO"
msg_status "$MESSAGE" "$STATUS"
}
msg_debug () {
MESSAGE="$1"
STATUS="DEBUG"
msg_status "$MESSAGE" "$STATUS"
}
msg_ok () {
MESSAGE="$1"
STATUS="OK"
msg_status "$MESSAGE" "$STATUS"
}
msg_not_ok () {
MESSAGE="$1"
STATUS="NOT_OK"
msg_status "$MESSAGE" "$STATUS"
}
msg_fail () {
MESSAGE="$1"
STATUS="FAILED"
msg_status "$MESSAGE" "$STATUS"
}
msg_success () {
MESSAGE="$1"
STATUS="SUCCESS"
msg_status "$MESSAGE" "$STATUS"
}
msg_passed () {
MESSAGE="$1"
STATUS="PASSED"
msg_status "$MESSAGE" "$STATUS"
}
check_status () {
CMD="$1"
STATUS="$2"
if [ "$STATUS" == "0" ]
then
msg_ok "$CMD"
else
msg_fail "$CMD"
fi
}
#
# Private function
#
# This is a function that just positions
# the cursor one row up and to the right.
# It then prints a message with specified
# Color
# It is used for displaying colored status messages on the
# Right side of the screen.
#
# ARG1 = "status message (OK / FAIL)"
# ARG2 = The color in which the status is displayed.
#
raw_status () {
STATUS="$1"
COLOR="$2"
function position_cursor () {
let RES_COL=`tput cols`-12
tput cuf $RES_COL
tput cuu1
}
position_cursor
echo -n "["
$DEFAULT
$BOLD
$COLOR
echo -n "$STATUS"
$DEFAULT
echo "]"
# log "Status = $STATUS"
}
#
# This function converts a status message to a particular color.
#
status_color () {
STATUS="$1"
case $STATUS in
EMERGENCY )
STATUS="EMERGENCY"
COLOR="$RED"
;;
ALERT )
STATUS=" ALERT "
COLOR="$RED"
;;
CRITICAL )
STATUS="CRITICAL "
COLOR="$RED"
;;
ERROR )
STATUS=" ERROR "
COLOR="$RED"
;;
WARNING )
STATUS=" WARNING "
COLOR="$YELLOW"
;;
NOTICE )
STATUS=" NOTICE "
COLOR="$BLUE"
;;
INFO )
STATUS=" INFO "
COLOR="$LIGHT_BLUE"
;;
DEBUG )
STATUS=" DEBUG "
COLOR="$DEFAULT"
;;
OK )
STATUS=" OK "
COLOR="$GREEN"
;;
NOT_OK)
STATUS=" NOT OK "
COLOR="$RED"
;;
PASSED )
STATUS=" PASSED "
COLOR="$GREEN"
;;
SUCCESS )
STATUS=" SUCCESS "
COLOR="$GREEN"
;;
FAILURE | FAILED )
STATUS=" FAILED "
COLOR="$RED"
;;
*)
STATUS="UNDEFINED"
COLOR="$YELLOW"
esac
}
display_status () {
raw_status "$STATUS" "$COLOR"
}
#
# Exit with error status
#
bail () {
ERROR="$?"
MSG="$1"
if [ ! "$ERROR" = "0" ]
then
msg_fail "$MSG"
exit "$ERROR"
fi
}
#
# This function executes a command provided as a parameter
# The function then displays if the command succeeded or not.
#
cmd () {
COMMAND="$1"
msg "Executing: $COMMAND"
RESULT=`$COMMAND 2>&1`
ERROR="$?"
MSG="Command: ${COMMAND:0:29}..."
tput cuu1
if [ "$ERROR" == "0" ]
then
msg_ok "$MSG"
if [ "$DEBUG" == "1" ]
then
msg "$RESULT"
fi
else
msg_fail "$MSG"
log "$RESULT"
fi
return "$ERROR"
}
#
# These functions can be used for timing how long (a) command(s) take to
# execute.
#
now () {
echo $(date +%s)
}
elapsed () {
START="$1"
STOP="$2"
echo $(( STOP - START ))
}
#
# Prints an error message ($2) to stderr and exits with the return code ($1).
# The message is also logged.
#
function die {
local -r err_code="$1"
local -r err_msg="$2"
local -r err_caller="${3:-$(caller 0)}"
msg_fail "ERROR: $err_msg"
msg_fail "ERROR: At line $err_caller"
msg_fail "ERROR: Error code = $err_code"
exit "$err_code"
} >&2 # function writes to stderr
#
# Check if a return code ($1) indicates an error (i.e. >0) and prints an error
# message ($2) to stderr and exits with the return code ($1).
# The error is also logged.
#
# Die if error code is false.
#
function die_if_false {
local -r err_code=$1
local -r err_msg=$2
local -r err_caller=$(caller 0)
if [[ "$err_code" != "0" ]]
then
die $err_code "$err_msg" "$err_caller"
fi
} >&2 # function writes to stderr
#
# Dies when error code is true
#
function die_if_true {
local -r err_code=$1
local -r err_msg=$2
local -r err_caller=$(caller 0)
if [[ "$err_code" == "0" ]]
then
die $err_code "$err_msg" "$err_caller"
fi
} >&2 # function writes to stderr
#
# Replace some text inside a string.
#
function str_replace () {
local ORIG="$1"
local DEST="$2"
local DATA="$3"
echo "$DATA" | sed "s/$ORIG/$DEST/g"
}
#
# Replace string of text in file.
# Uses the ed editor to replace the string.
#
# arg1 = string to be matched
# arg2 = new string that replaces matched string
# arg3 = file to operate on.
#
function str_replace_in_file () {
local ORIG="$1"
local DEST="$2"
local FILE="$3"
has_value FILE
die_if_false $? "Empty argument 'file'"
file_exists "$FILE"
die_if_false $? "File does not exist"
sed -i "s/$ORIG/$DEST/g" $FILE
#printf ",s/$ORIG/$DEST/g\nw\nQ" | ed -s "$FILE" > /dev/null 2>&1
return "$?"
}
checkroot () {
if [[ $EUID -ne 0 ]]; then
warn "This script must be run as root or:" 1>&2
pass "\$ sudo $0"
exit 1
fi
}
# Download if file does not exits: $1=url $1=path
download () {
msg "Downloading: $1"
if [ -f "$2" ]
then
msg "You already have $1. Download skipped."
else
wget -O $2 $1; bail "Downloading of "$1" failed."
fi
}
AttemptsFunc() {
counter=$1
$2
while [ $? -gt 0 ]; do
let counter=counter-1
warn "Fail. You have $counter more attempts.\n"
if [ $counter -eq 0 ]; then
warn "\nTo much unsuccesfull attempts. Quiting."
exit 1
fi
$2
done
}
# Usage: $ question "Do you?" 'echo "If answer is yes"' 'echo "If answer is no"'
question () {
log "Question: $1"
read -p "$1 (y/n)?" -n 1
if [[ ! $REPLY =~ ^[Yy]$ ]]
then
echo ""
msg "Answered: No."
eval $3
else
echo ""
msg "Answered: Yes."
eval $2
fi
}
# Remove tmp dir
delete_tmp () {
msg_notice "Cleaning tmp filder..."
question "Do you want to remove tmp folder: "$tmp_dir"" 'rm -rf "$tmp_dir"' 'echo "Leaving tmp folder"'
}
# Measure Elapsed Time
# Measure start with command: tmr=$(timer)
function timer()
{
if [[ $# -eq 0 ]]; then
echo $(date '+%s')
else
local stime=$1
etime=$(date '+%s')
if [[ -z "$stime" ]]; then stime=$etime; fi
dt=$((etime - stime))
ds=$((dt % 60))
dm=$(((dt / 60) % 60))
dh=$((dt / 3600))
printf '%d:%02d:%02d' $dh $dm $ds
fi
}
# print elapsed time as info
function print_elapsed() {
elapsed=$(printf 'Elapsed time: %s\n' $(timer $tmr))
msg_info "$elapsed"
}
init