-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathbash-utils.sh
More file actions
2327 lines (2032 loc) · 82.8 KB
/
bash-utils.sh
File metadata and controls
2327 lines (2032 loc) · 82.8 KB
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
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# QUICK EDIT: FILE="/tmp/bash-utils.sh" && rm -fv $FILE && nano $FILE && chmod 555 $FILE && /tmp/bash-utils.sh bashUtilsSetup
# NOTE: For this script to work properly the KIRA_GLOBS_DIR env variable should be set to "/var/kiraglob" or equivalent & the directory should exist
REGEX_DNS="^(([a-zA-Z](-?[a-zA-Z0-9])*)\.)+[a-zA-Z]{2,}$"
REGEX_IP="^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$"
REGEX_NODE_ID="^[a-f0-9]{40}$"
REGEX_TXHASH="^[a-fA-F0-9]{64}$"
REGEX_SHA256="^[a-fA-F0-9]{64}$"
REGEX_MD5="^[a-fA-F0-9]{32}$"
REGEX_INTEGER="^-?[0-9]+$"
REGEX_NUMBER="^[+-]?([0-9]*[.])?([0-9]+)?$"
REGEX_PUBLIC_IP='^([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(?<!172\.(16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31))(?<!127)(?<!^10)(?<!^0)\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(?<!192\.168)(?<!172\.(16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31))\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(?<!\.255$)(?<!\b255.255.255.0\b)(?<!\b255.255.255.242\b)$'
REGEX_CIRD="^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\/([0-9]|[1-2][0-9]|3[0-2])$"
REGEX_KIRA="^(kira)[a-zA-Z0-9]{39}$"
REGEX_VERSION="^(v?)([0-9]+)\.([0-9]+)\.([0-9]+)(-?)([a-zA-Z]+)?(\.?([0-9]+)?)$"
REGEX_CID="^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})$"
# NOTE: Important! in the REGEX_URL the ' quote character must be used instead of ", do NOT modify this string
REGEX_URL1='[-A-Za-z0-9\+&@#/%?=~_|!:,.;]*[-A-Za-z0-9\+&@#/%=~_|]\.[-A-Za-z0-9\+&@#/%?=~_|!:,.;]*[-A-Za-z0-9\+&@#/%=~_|]$'
REGEX_URL2="^(https?|ftp|file)://$REGEX_URL1"
UBUNTU_AGENT="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.85 Safari/537.36"
function bashUtilsVersion() {
bashUtilsSetup "version" 2> /dev/null || bu bashUtilsSetup "version"
}
# this is default installation script for utils
# ./bash-utils.sh bashUtilsSetup "/var/kiraglob"
function bashUtilsSetup() {
local BASH_UTILS_VERSION="v0.3.52"
local COSIGN_VERSION="v2.0.0"
if [ "$1" == "version" ] ; then
echo "$BASH_UTILS_VERSION"
return 0
else
local GLOBS_DIR="$1"
local UTILS_SOURCE=$(realpath "$0")
local VERSION=$($UTILS_SOURCE bashUtilsVersion || echo '')
local UTILS_DESTINATION="/usr/local/bin/bash-utils.sh"
if [ -z "$GLOBS_DIR" ] ; then
[ -z "$KIRA_GLOBS_DIR" ] && KIRA_GLOBS_DIR="/var/kiraglob"
else
KIRA_GLOBS_DIR=$GLOBS_DIR
fi
echo "INFO: Loaded utils from '$UTILS_SOURCE', installing bash-utils & setting up glob dir in '$KIRA_GLOBS_DIR'..."
if [ "$VERSION" != "$BASH_UTILS_VERSION" ] ; then
bu echoErr "ERROR: Self check version mismatch, expected '$BASH_UTILS_VERSION', but got '$VERSION'"
return 1
elif [ "$UTILS_SOURCE" == "$UTILS_DESTINATION" ] ; then
bu echoErr "ERROR: Installation source script and destination can't be the same"
return 1
elif [ ! -f "$UTILS_SOURCE" ] ; then
bu echoErr "ERROR: utils source was NOT found"
return 1
else
mkdir -p "/usr/local/bin" "/bin" "/tmp"
cp -fv "$UTILS_SOURCE" "$UTILS_DESTINATION"
cp -fv "$UTILS_SOURCE" "/usr/local/bin/bash-utils"
cp -fv "$UTILS_SOURCE" "/usr/local/bin/bu"
cp -fv "$UTILS_SOURCE" "/bin/bu"
chmod +x "$UTILS_DESTINATION" "/usr/local/bin/bash-utils" "/usr/local/bin/bu" "/bin/bu"
local SUDOUSER="${SUDO_USER}"
local USERNAME="${USER}"
local LOGNAME=$(logname 2> /dev/null echo "")
[ "$SUDOUSER" == "root" ] && SUDOUSER=""
[ "$USERNAME" == "root" ] && USERNAME=""
[ "$LOGNAME" == "root" ] && LOGNAME=""
local TARGET="/$LOGNAME/.bashrc"
[ -f $TARGET ] && chmod 777 $TARGET && echoInfo "INFO: /etc/profile executable target set to $TARGET"
TARGET="/$USERNAME/.bashrc" && [ -f $TARGET ] && chmod 777 $TARGET && echoInfo "INFO: /etc/profile executable target set to $TARGET"
TARGET="/$SUDOUSER/.bashrc" && [ -f $TARGET ] && chmod 777 $TARGET && echoInfo "INFO: /etc/profile executable target set to $TARGET"
TARGET="/root/.bashrc" && [ -f $TARGET ] && chmod 777 $TARGET && echoInfo "INFO: /etc/profile executable target set to $TARGET"
TARGET=~/.bashrc && [ -f $TARGET ] && chmod 777 $TARGET && echoInfo "INFO: /etc/profile executable target set to $TARGET"
TARGET=~/.zshrc && [ -f $TARGET ] && chmod 777 $TARGET && echoInfo "INFO: /etc/profile executable target set to $TARGET"
TARGET=~/.profile && [ -f $TARGET ] && chmod 777 $TARGET && echoInfo "INFO: /etc/profile executable target set to $TARGET"
mkdir -p "$KIRA_GLOBS_DIR"
bu setGlobEnv KIRA_GLOBS_DIR "$KIRA_GLOBS_DIR"
bu setGlobEnv KIRA_TOOLS_SRC "$UTILS_DESTINATION"
bu setGlobPath "/usr/local/bin"
bu setGlobPath "/bin"
local AUTOLOAD_SET=$(bu getLastLineByPrefix "source $UTILS_DESTINATION" /etc/profile 2> /dev/null || echo "-1")
if [[ $AUTOLOAD_SET -lt 0 ]] ; then
echo "source $UTILS_DESTINATION || echo \"ERROR: Failed to load kira bash-utils from '$UTILS_DESTINATION'\"" >> /etc/profile
fi
bu loadGlobEnvs
bu echoInfo "INFO: SUCCESS!, Installed kira bash-utils $(bu bashUtilsVersion)"
fi
OLD_COSIGN_VER="$(timeout 30 cosign version --json 2>&1 | bu jsonParse "gitVersion" || echo "v0.0.0")"
if [[ $(versionToNumber "$OLD_COSIGN_VER") -lt $(versionToNumber "$COSIGN_VERSION") ]] ; then
bu echoWarn "WARNING: Cosign tool is not installed or requires update $OLD_COSIGN_VER -> $COSIGN_VERSION..."
declare -l ARCH="$(uname -m)"
[[ "$ARCH" == *"ar"* ]] && ARCH="arm64" || ARCH="amd64"
declare -l PLATFORM="$(uname)"
declare -l FILE_NAME=$(echo "cosign-${PLATFORM}-${ARCH}")
TMP_FILE="/tmp/${FILE_NAME}.tmp"
rm -fv "$TMP_FILE"
wget --user-agent="$UBUNTU_AGENT" https://github.com/sigstore/cosign/releases/download/${COSIGN_VERSION}/$FILE_NAME -O "$TMP_FILE" && \
chmod +x -v "$TMP_FILE" && mv -fv "$TMP_FILE" /usr/local/bin/cosign && \
cosign version || bu echoErr "ERROR: Failed to install cosign tool, some BU commands might NOT function."
fi
fi
}
# bash 3 (MAC) compatybility
# "$(toLower "$1")"
function toLower() {
declare -l v="$1"
echo "$v"
}
# bash 3 (MAC) compatybility
# "$(toUpper "$1")"
function toUpper() {
declare -u v="$1"
echo "$v"
}
# bash 3 (MAC) compatybility
# capitalizes first leter of a string
# e.g. toCapital "quick brown fox" -> "Quick brown fox"
function toCapital() {
echo "$(toUpper "$(echo "$1" | cut -c1)")$(echo "$1" | cut -c2-)"
}
function isNullOrEmpty() {
case "$1" in
"") echo "true" ;;
"null") echo "true" ;;
"Null") echo "true" ;;
"NULL") echo "true" ;;
"nil") echo "true" ;;
"Nil") echo "true" ;;
"NIL") echo "true" ;;
*) echo "false" ;;
esac
}
function delWhitespaces() {
echo "$1" | tr -d '\011\012\013\014\015\040'
}
function isNullOrWhitespaces() {
case "$1" in
""|[[:space:]]*) echo "true" ;;
*) isNullOrEmpty "$1" ;;
esac
}
function isKiraAddress() {
if ($(isNullOrEmpty "$1")) ; then echo "false" ; else [[ "$1" =~ $REGEX_KIRA ]] && echo "true" || echo "false" ; fi
}
function isTxHash() {
if ($(isNullOrEmpty "$1")) ; then echo "false" ; else [[ "$1" =~ $REGEX_TXHASH ]] && echo "true" || echo "false" ; fi
}
function isSHA256() {
if ($(isNullOrEmpty "$1")) ; then echo "false" ; else [[ "$1" =~ $REGEX_SHA256 ]] && echo "true" || echo "false" ; fi
}
function isMD5() {
if ($(isNullOrEmpty "$1")) ; then echo "false" ; else [[ "$1" =~ $REGEX_MD5 ]] && echo "true" || echo "false" ; fi
}
function isDns() {
if ($(isNullOrEmpty "$1")) ; then echo "false" ; else [[ "$1" =~ $REGEX_DNS ]] && echo "true" || echo "false" ; fi
}
function isIp() {
if ($(isNullOrEmpty "$1")) ; then echo "false" ; else [[ "$1" =~ $REGEX_IP ]] && echo "true" || echo "false" ; fi
}
function isPublicIp() {
if ($(isNullOrEmpty "$1")) ; then echo "false" ; else [ "$(echo "$1" | grep -P $REGEX_PUBLIC_IP | xargs || echo \"\")" == "$1" ] && echo "true" || echo "false" ; fi
}
function isDnsOrIp() {
if ($(isNullOrEmpty "$1")) ; then echo "false" ; else
local VAR="false"
($(isDns "$1")) && VAR="true"
[ "$VAR" != "true" ] && ($(isIp "$1")) && VAR="true"
echo $VAR
fi
}
# Notation check "xxx.xxx.xxx.xxx/xx"
# e.g.: isCIDR 172.22.24.212/20
function isCIDR() {
if ($(isNullOrEmpty "$1")) ; then echo "false" ; else [[ "$1" =~ $REGEX_CIRD ]] && echo "true" || echo "false" ; fi
}
function isInteger() {
if ($(isNullOrEmpty "$1")) ; then echo "false" ; else [[ $1 =~ $REGEX_INTEGER ]] && echo "true" || echo "false" ; fi
}
function isBoolean() {
if ($(bu isNullOrEmpty "$1")) ; then echo "false" ; else
declare -l val="$1"
if [ "$val" == "false" ] || [ "$val" == "true" ] ; then echo "true"
else echo "false" ; fi
fi
}
function isNodeId() {
if ($(isNullOrEmpty "$1")) ; then echo "false" ; else [[ "$1" =~ $REGEX_NODE_ID ]] && echo "true" || echo "false" ; fi
}
function isNumber() {
if ($(bu isNullOrEmpty "$1")) ; then echo "false" ; else [[ "$1" =~ $REGEX_NUMBER ]] && echo "true" || echo "false" ; fi
}
function isNaturalNumber() {
( [ ! -z "$1" ] && ( ! [[ "$1" =~ [^0-9] ]] ) && [[ "$1" -ge 0 ]] 2> /dev/null ) && echo "true" || echo "false"
}
function isLetters() {
( [ -z "$1" ] || [[ "$1" =~ [^a-zA-Z] ]] ) && echo "false" || echo "true"
}
function isAlphanumeric() {
( [ -z "$1" ] || [[ "$1" =~ [^a-zA-Z0-9] ]] ) && echo "false" || echo "true"
}
function isPort() {
( ($(isNaturalNumber $1)) && (($1 > 0)) && (($1 < 65536)) ) && echo "true" || echo "false"
}
function isMnemonic() {
local MNEMONIC=$(echo "$1" | xargs 2> /dev/null || echo -n "")
local COUNT=$(echo "$MNEMONIC" | wc -w 2> /dev/null || echo -n "")
(! $(isNaturalNumber $COUNT)) && COUNT=0
# Ensure that string only contains words
if [[ $MNEMONIC =~ ^[[:alpha:][:space:]]*$ ]] ; then
if (( $COUNT % 3 == 0 )) && [[ $COUNT -ge 12 ]] ; then echo "true" ; else echo "false" ; fi
else
echo "false"
fi
}
function isVersion {
[[ "$1" =~ $REGEX_VERSION ]] && echo "true" || echo "false"
}
function isCID() {
if ($(isNullOrEmpty "$1")) ; then echo "false" ; else [[ "$1" =~ $REGEX_CID ]] && echo "true" || echo "false" ; fi
}
function date2unix() {
local DATE_TMP=""
[ -z "$*" ] && DATE_TMP="$(timeout 1 cat 2> /dev/null || echo "")" || DATE_TMP="$*"
DATE_TMP=$(echo "$DATE_TMP" | xargs 2> /dev/null || echo -n "")
if (! $(isNullOrWhitespaces "$DATE_TMP")) && (! $(isNaturalNumber $DATE_TMP)) ; then
DATE_TMP=$(date -d "$DATE_TMP" +"%s" 2> /dev/null || echo "0")
fi
($(isNaturalNumber "$DATE_TMP")) && echo "$DATE_TMP" || echo "0"
}
function isPortOpen() {
local ADDRESS=$1
local PORT=$2
local TIMEOUT=$3
(! $(isNaturalNumber $TIMEOUT)) && TIMEOUT=1
if (! $(isDnsOrIp $ADDRESS)) || (! $(isPort $PORT)) ; then echo "false"
elif timeout $TIMEOUT nc -z $ADDRESS $PORT ; then echo "true"
else echo "false" ; fi
}
function fileSize() {
local BYTES=$(stat -c%s $1 2> /dev/null || echo -n "")
($(isNaturalNumber "$BYTES")) && echo "$BYTES" || echo -n "0"
}
function isFileEmpty() {
local FILE="$1"
if [ -z "$FILE" ] || [ ! -f "$FILE" ] || [ ! -s "$FILE" ] ; then echo "true" ; else
local TEXT=$(head -c 64 "$FILE" 2>/dev/null | tr -d '\0\011\012\013\014\015\040' 2>/dev/null || echo '')
[ -z "$TEXT" ] && TEXT=$(tail -c 64 "$FILE" 2>/dev/null | tr -d '\0\011\012\013\014\015\040' 2>/dev/null || echo '')
[ -z "$TEXT" ] && TEXT=$(cat $FILE | tr -d '\0\011\012\013\014\015\040' 2>/dev/null || echo -n "")
[ ! -z "$TEXT" ] && echo "false" || echo "true"
fi
}
function isSameFile() {
local FILE1="$1"
local FILE2="$2"
if [ ! -z $FILE1 ] && [ -f $FILE1 ] && [ ! -z $FILE2 ] && [ -f $FILE2 ] ; then
echo $(cmp --silent $FILE1 $FILE2 && echo "true" || echo "false")
else
echo "false"
fi
}
# Example use case: [[ $(versionToNumber "v0.0.0.3") -lt $(versionToNumber "v1.0.0.2") ]] && echo true || echo false
function versionToNumber() {
local version=""
[ -z "$1" ] && version="$(timeout 1 cat 2> /dev/null || echo "")" || version="$1"
version=$(echo "$version" | tr -d [a-z,A-Z] | sed "s/-././g" | sed "s/+/./g" | sed "s/-//g" | tr -d ' ')
local major=$(echo $version | cut -d. -f1 | sed 's/[^0-9]*//g' 2> /dev/null || echo "0")
local minor=$(echo $version | cut -d. -f2 | sed 's/[^0-9]*//g' 2> /dev/null || echo "0")
local micro=$(echo $version | cut -d. -f3 | sed 's/[^0-9]*//g' 2> /dev/null || echo "0")
local build=$(echo $version | cut -d. -f4 | sed 's/[^0-9]*//g' 2> /dev/null || echo "0")
local sum=0
(! $(isNaturalNumber "$major")) && major=0
(! $(isNaturalNumber "$minor")) && minor=0
(! $(isNaturalNumber "$micro")) && micro=0
(! $(isNaturalNumber "$build")) && build=0
sum=$(( sum + ( 1 * build ) )) && [[ $build -le 0 ]] && build=0
sum=$(( sum + ( 10000 * micro ) )) && [[ $micro -le 0 ]] && micro=10000
sum=$(( sum + ( 100000000 * minor ) )) && [[ $minor -le 0 ]] && minor=100000000
sum=$(( sum + ( 1000000000000 * major) )) && [[ $major -le 0 ]] && major=1000000000000
echo $sum
}
function sha256() {
if [ -z "$1" ] ; then
echo $(cat | sha256sum | awk '{ print $1 }' | xargs || echo -n "") || echo -n ""
else
[ -f $1 ] && echo $(sha256sum $1 | awk '{ print $1 }' | xargs || echo -n "") || echo -n ""
fi
}
function md5() {
if [ -z "$1" ] ; then
echo $(cat | md5sum | awk '{ print $1 }' | xargs || echo -n "") || echo -n ""
else
[ -f $1 ] && echo $(md5sum $1 | awk '{ print $1 }' | xargs || echo -n "") || echo -n ""
fi
}
function strLength() {
[ "$1" == "-e" ] && echo "2" && return 0
local result=""
[ -z "$1" ] && result="0" || result=$(echo "$1" | awk '{print length}') || result=-1
[[ "$result" -gt 0 ]] 2> /dev/null && echo $result || echo -1
}
function strFirstN() {
local string="$1"
local n="$2"
if [ ! -z "$n" ] && [[ "$n" -gt 0 ]] 2> /dev/null ; then
local string_len=$(strLength "$string")
[[ $string_len -le $n ]] && echo "$string" || echo "${string:0:n}"
else
echo ""
fi
}
function strLastN() {
local string="$1"
local n="$2"
if [ ! -z "$n" ] && [[ "$n" -gt 0 ]] 2> /dev/null ; then
local string_len=$(strLength "$string")
[[ $string_len -le $n ]] && echo "$string" || echo "${string: -n}"
else
echo ""
fi
}
# shortens string if possible by taking N prefix and N suffix characters and combining it with separator
# e.g. strShort "123456789" 1 "..."" -> 1...9
function strShort() {
local string="$1"
local trim_len=""
( [ ! -z "$2" ] && [[ "$2" -gt 0 ]] 2> /dev/null ) && trim_len="$2" || trim_len=3
local separator="$3"
[ -z "$separator" ] && separator="..."
local string_len=$(strLength "$string")
local separator_len=$(strLength "$separator")
local final_len=$(((trim_len * 2) + separator_len ))
[[ $string_len -le $final_len ]] && echo "$string" || echo "$(strFirstN "$string" $trim_len)${separator}$(strLastN "$string" $trim_len)"
}
# shorten string to exact number of characters with a separator
# e.g. strShort 123456789" 5 '.' -> 1...9
function strShortN() {
local string="$1"
local max_len=""
local separator="$3"
local string_len=$(strLength "$string")
( [ ! -z "$2" ] && [[ "$2" -gt 0 ]] 2> /dev/null ) && max_len="$2" || ( echo "" && return 0 )
( [ -z "$separator" ] || [[ $(strLength "$separator") -gt 1 ]] ) && separator="."
if [[ $max_len -le 0 ]] ; then
echo ""
elif [[ $max_len -ge $string_len ]] ; then # same or greater lenght, skip processing
echo "$string"
elif [[ $max_len -le 1 ]] ; then # if sting can be just a single char then just display separator: '.'
echo "$separator"
elif [[ $max_len -eq 2 ]] ; then # if sting can be just a single char then just display separator: 'a.'
echo "$(strFirstN "$string" 1)$separator"
elif [[ $max_len -eq 3 ]] ; then # if sting can be just 3 char then just display first and last: 'a..'
echo "$(strFirstN "$string" 1)${separator}${separator}"
elif [[ $max_len -eq 4 ]] ; then # if sting can be just 4 char then just display 1 first and 1 last: 'a..b'
echo "$(strFirstN "$string" 1)${separator}${separator}${separator}"
else
local side_len=$(((max_len - 3) / 2 ))
local final_len=$(((side_len * 2) + 3))
[[ $final_len -ne $max_len ]] && echo "$(strFirstN "$string" $((side_len + 1)))${separator}${separator}${separator}$(strLastN "$string" $side_len)" || echo "$(strShort "$string" $side_len "${separator}${separator}${separator}")"
fi
}
# repeats string N times
# e.g.: strRepeat "a" 30 -> aaa...
strRepeat(){
if [ "$1" == "-" ] || [ "$1" == "%" ] ; then
[[ "$2" -gt 0 ]] 2> /dev/null && echo "$(printf "%${2}s" | sed "s/ /${1}/g")" || echo ""
else
[[ "$2" -gt 0 ]] 2> /dev/null && echo "$(printf "$1"'%.s' $(eval "echo {1.."$(($2))"}"))" || echo ""
fi
}
# fixes string to specific length to the left with filler padding
# e.g.: echo "| $(strFixL "123456789" 15) |" -> | 123456789 |
function strFixL() {
local string="$1"
local max_len=""
local separator="$3"
local filler="$4"
( [ ! -z "$2" ] && [[ "$2" -gt 0 ]] 2> /dev/null ) && max_len="$2" || max_len="0"
[ -z "$separator" ] && separator="."
[ -z "$filler" ] && filler=" "
filler=$(strRepeat "$filler" $max_len)
echo "$(strFirstN "$(strShortN "$string" $max_len "$separator")$filler" $max_len)"
}
# fixes string to specific length to the left with filler padding
# e.g.: echo "| $(strFixR "123456789" 15) |" -> | 123456789 |
function strFixR() {
local string="$1"
local max_len="$2"
local separator="$3"
local filler="$4"
( [ ! -z "$2" ] && [[ "$2" -gt 0 ]] 2> /dev/null ) && max_len="$2" || max_len="0"
[ -z "$separator" ] && separator="."
[ -z "$filler" ] && filler=" "
filler=$(strRepeat "$filler" $max_len)
echo "$(strLastN "${filler}$(strShortN "$string" $max_len "$separator")" $max_len)"
}
# fixes string to specific length to the center with filler padding
# e.g.: echo "| $(strFixC "123456789" 15) |" -> | 123456789 |
function strFixC() {
local string="$1"
local max_len="$2"
local separator="$3"
local filler="$4"
( [ ! -z "$2" ] && [[ "$2" -gt 0 ]] 2> /dev/null ) && max_len="$2" || max_len="0"
[ -z "$separator" ] && separator="."
[ -z "$filler" ] && filler=" "
local filler_extr=$(strRepeat "$filler" $max_len)
local string_len=$(strLength "$string")
if [[ $string_len -ge $max_len ]] ; then
echo "$(strFixL "$string" "$max_len" "$separator" "$filler")"
else
local remaining=$((max_len - string_len))
local side_len=$((remaining / 2))
local filler_extr=$(strRepeat "$filler" $side_len)
[[ $((remaining % 2)) -eq 0 ]] && echo "${filler_extr}${string}${filler_extr}" || echo "${filler_extr}${string}${filler_extr}${filler}"
fi
}
function strStartsWith() {
local string="$1"
local prefix="$2"
local string_len=$(strLength "$string")
local prefix_len=$(strLength "$prefix")
if [[ $prefix_len -eq $string_len ]] && [[ $string_len -ge 1 ]] ; then
[ "$string" == "$prefix" ] && echo "true" && return 0 || echo "false" && return 0
elif [[ $prefix_len -le $string_len ]] && [[ $prefix_len -ge 1 ]] && [[ $string_len -ge 1 ]] ; then
local substr="${string:0:$prefix_len}"
[ "$substr" == "$prefix" ] && echo "true" && return 0 || echo "false" && return 0
fi
echo "false"
}
function strEndsWith() {
local string="$1"
local suffix="$2"
local string_len=$(strLength "$string")
local suffix_len=$(strLength "$suffix")
if [[ $suffix_len -eq $string_len ]] && [[ $string_len -ge 1 ]] ; then
[ "$string" == "$suffix" ] && echo "true" && return 0 || echo "false" && return 0
elif [[ $suffix_len -le $string_len ]] && [[ $suffix_len -ge 1 ]] && [[ $string_len -ge 1 ]] ; then
local n="-${suffix_len}"
local substr="${string:$n}"
[ "$substr" == "$suffix" ] && echo "true" && return 0 || echo "false" && return 0
fi
echo "false"
}
# splits string by specific character and takes n'th element (indexed starting at 0)
# e.g.: strSplitTakeN , 2 "a,b,c"
function strSplitTakeN() {
local IFS="$1"
local arr=($3)
echo "${arr[$2]}"
}
# trims string from whitespace characters but not newlines etc
function strTrim() {
local str="$1"
str=${str##*( )}
str=${str%%*( )}
echo "$str"
}
# getArgs --test="lol1" --tes-t="lol-l" --test2="lol 2" -e=ok -t=ok2 --silent=true --invisible=yes
# internally supported flags:
# gargs_verbose (default true), gargs_throw (default true)
# getArgs --gargs_throw=false --gargs_verbose=false --test="lol1" --tes-t="lol-l" --test2="lol 2" -e=ok -t=ok2 --silent=true --invisible=yes "lol"
function getArgs() {
local gargs_verbose="true"
local gargs_throw="true"
for arg in "$@" ; do
[ -z "$arg" ] && continue
[[ "$arg" =~ ^-[^-].* ]] && arg="-${arg}"
if [[ "$arg" == "--"*"="* ]] && [[ "$arg" != "--="* ]] ; then
local arg_len=$(echo "$arg" | awk '{print length}')
local prefix=$(echo $arg | cut -d'=' -f1)
local prefix_len=$(echo "$prefix" | awk '{print length}')
local n="-$((arg_len - prefix_len - 1))"
local val="${arg:$n}"
prefix="$(echo $prefix | sed -z 's/^-*//')"
local key=$(echo "$prefix" | tr '-' '_')
case "$arg" in
"-$key=''") val="" ;;
"-$key=\"\"") val="" ;;
"--$key=''") val="" ;;
"--$key=\"\"") val="" ;;
"--$key=") val="" ;;
"-$key=") val="" ;;
esac
case "$key" in
"gargs_verbose") [ "$val" == "false" ] && gargs_verbose="false" && continue || continue ;;
"gargs_throw") [ "$val" == "false" ] && gargs_throw="false" && continue || continue ;;
esac
[ "$gargs_verbose" == "true" ] && echoInfo "$key='$val'"
if [ "$gargs_throw" == "true" ]; then
eval $key="'$val'"
else
eval $key="'$val'" || :
fi
else
[ "$gargs_verbose" == "true" ] && echoErr "ERROR: Invalid argument '$arg', missing name, '--' and/or '=' operators ($gargs_throw)"
[ "$gargs_throw" == "true" ] && return 1
fi
done
# eval returns non 0 code, ensure to return 0
return 0
}
# counts number of characters in a string
# strCntChar "1,2,3,4,5" ","
function strCntChar() {
local str="$1"
local char="$2"
local cnt=0
if [ ! -z "$str" ] && [ ! -z "$char" ] ; then
cnt="$(echo "$str" | grep -o "$char" | wc -l || echo "0")"
fi
(! $(isNaturalNumber "$cnt")) && cnt="0"
echo "$cnt"
}
# converts character separated ranges to whitespace separated unique ordered string
# arr=($(strRangesToArr "1-3,4,6-7" , -)) ; echo "${arr[*]}" -> "1 2 3 4 6 7"
strRangesToArr() {
local ranges="$1"
local char1="$2"
local char2="$3"
[ -z "$char1" ] && char1=","
[ -z "$char2" ] && char2="-"
local ranges_cnt=$(strCntChar "$ranges" "$char1")
local res_arr=()
local i=0
local valStart=0
local valEnd=0
while [[ $i -le $ranges_cnt ]] ; do
range="$(delWhitespaces $(strSplitTakeN "$char1" $i "$ranges"))"
i=$((i + 1))
($(isNumber "$range")) && res_arr+=($range) && continue
valStart="$(delWhitespaces $(strSplitTakeN "$char2" 0 "$range"))"
valEnd="$(delWhitespaces $(strSplitTakeN "$char2" 1 "$range"))"
( (! $(isNumber "$valStart")) || (! $(isNumber "$valStart")) ) && continue
if [[ $valStart -gt $valEnd ]] ; then
res_arr+=($(seq $valEnd $valStart))
else
res_arr+=($(seq $valStart $valEnd))
fi
done
res_arr=($(echo "${res_arr[*]}" | tr ' ' '\n' | sort -u -n | tr '\n' ' '))
local OLDIFS=$IFS
local IFS=' '
local result="${res_arr[*]}"
local IFS=$OLDIFS
echo "$result"
}
# get default network interface
function getNetworkIface() {
echo "$(netstat -rn 2> /dev/null | grep -m 1 UG | awk '{print $8}' | xargs 2> /dev/null || echo -n "")"
}
# get network interfaces
function getNetworkIfaces() {
echo "$(ifconfig | cut -d ' ' -f1 | tr ':' '\n' | awk NF)"
}
function getPublicIp() {
local public_ip=$(dig TXT +short o-o.myaddr.l.google.com @ns1.google.com +time=5 +tries=1 2> /dev/null | awk -F'"' '{ print $2}' 2> /dev/null || echo -n "")
( ! $(isDnsOrIp "$public_ip")) && public_ip=$(dig +short @resolver1.opendns.com myip.opendns.com +time=5 +tries=1 2> /dev/null | awk -F'"' '{ print $1}' 2> /dev/null || echo -n "")
( ! $(isDnsOrIp "$public_ip")) && public_ip=$(dig +short @ns1.google.com -t txt o-o.myaddr.l.google.com -4 2> /dev/null | xargs 2> /dev/null || echo -n "")
( ! $(isDnsOrIp "$public_ip")) && public_ip=$(timeout 3 curl --silent https://ipinfo.io/ip | xargs 2> /dev/null || echo -n "")
( ! $(isDnsOrIp "$public_ip")) && echo "" || echo "$public_ip"
}
# returns ip of the defined local network interface otherwise checks default
# .e.g getLocalIp "$(globGet IFACE)"
function getLocalIp() {
local default_iface="$1"
[ -z "$default_iface" ] && default_iface=$(getDefaultNetworkIface)
local local_ip=$(/sbin/ifconfig "$default_iface" | grep -i mask | awk '{print $2}' | cut -f2 2> /dev/null || echo -n "")
( ! $(isDnsOrIp "$local_ip")) && local_ip=$(hostname -I | awk '{ print $1}' 2> /dev/null || echo "0.0.0.0")
($(isDnsOrIp "$local_ip")) && echo "$local_ip" || echo "0.0.0.0"
}
# Host list: https://ipfs.github.io/public-gateway-checker
# Given file CID downloads content from a known public IPFS gateway
# ipfsGet <file> <CID>
# ipfsGet --file=<file> --cid=<CID> --timeout="30" --url="https://ipfs.example.com/ipfs"
function ipfsGet() {
local cid=""
local file=""
local url=""
local timeout=""
local tries=""
getArgs --gargs_throw=false --gargs_verbose=false "$1" "$2" "$3" "$4" "$5"
[ -z "$file" ] && file="$1"
(! $(isCID "$cid")) && cid="$2"
(! $(isNaturalNumber "$timeout")) && timeout=30
(! $(isNaturalNumber "$tries")) && tries=2
local PUB_URL=""
local DOWNLOAD_SUCCESS="false"
if ($(isCID "$cid")) ; then
echoInfo "INFO: Cleaning up '$file' and searching for available gatewys..."
if [ ! -z "$url" ] ; then
PUB_URL="${url}/${cid}"
if ( [ "$DOWNLOAD_SUCCESS" != "true" ] && [[ $(urlContentLength "$PUB_URL" $timeout) -gt 1 ]] ) ; then
wget --tries="$tries" --waitretry=1 --timeout="$timeout" --user-agent="$UBUNTU_AGENT" "$PUB_URL" -O "$file" && \
DOWNLOAD_SUCCESS="true" || echoWarn "WARNING: Faild download from ${url} :("
fi
fi
PUB_URL="https://gateway.ipfs.io/ipfs/${cid}"
if ( [ "$DOWNLOAD_SUCCESS" != "true" ] && [[ $(urlContentLength "$PUB_URL" $timeout) -gt 1 ]] ) ; then
wget --tries="$tries" --waitretry=1 --timeout="$timeout" --user-agent="$UBUNTU_AGENT" "$PUB_URL" -O "$file" && \
DOWNLOAD_SUCCESS="true" || echoWarn "WARNING: Faild download from gateway.ipfs.io :("
fi
PUB_URL="https://dweb.link/ipfs/${cid}"
if ( [ "$DOWNLOAD_SUCCESS" != "true" ] && [[ $(urlContentLength "$PUB_URL" $timeout) -gt 1 ]] ) ; then
wget --tries="$tries" --waitretry=1 --timeout="$timeout" --user-agent="$UBUNTU_AGENT" "$PUB_URL" -O "$file" && \
DOWNLOAD_SUCCESS="true" || echoWarn "WARNING: Faild download from dweb.link :("
fi
PUB_URL="https://ipfs.joaoleitao.org/ipfs/${cid}"
if ( [ "$DOWNLOAD_SUCCESS" != "true" ] && [[ $(urlContentLength "$PUB_URL" $timeout) -gt 1 ]] ) ; then
wget --tries="$tries" --waitretry=1 --timeout="$timeout" --user-agent="$UBUNTU_AGENT" "$PUB_URL" -O "$file" && \
DOWNLOAD_SUCCESS="true" || echoWarn "WARNING: Faild download from ipfs.joaoleitao.org :("
fi
PUB_URL="https://ipfs.kira.network/ipfs/${cid}"
if ( [ "$DOWNLOAD_SUCCESS" != "true" ] && [[ $(urlContentLength "$PUB_URL" $timeout) -gt 1 ]] ) ; then
wget --tries="$tries" --waitretry=1 --timeout="$timeout" --user-agent="$UBUNTU_AGENT" "$PUB_URL" -O "$file" && \
DOWNLOAD_SUCCESS="true" || echoWarn "WARNING: Faild download from ipfs.kira.network :("
fi
PUB_URL="https://ipfs.snggle.com/ipfs/${cid}"
if ( [ "$DOWNLOAD_SUCCESS" != "true" ] && [[ $(urlContentLength "$PUB_URL" $timeout) -gt 1 ]] ) ; then
wget --tries="$tries" --waitretry=1 --timeout="$timeout" --user-agent="$UBUNTU_AGENT" "$PUB_URL" -O "$file" && \
DOWNLOAD_SUCCESS="true" || echoWarn "WARNING: Faild download from ipfs.snggle.com :("
fi
if ( [ "$DOWNLOAD_SUCCESS" != "true" ] || [ ! -f "$file" ] ) ; then
echoErr "ERROR: Failed to locate or download '$cid' file from any public IPFS gateway :("
return 1
else
echoInfo "INFO: Success, file '$cid' was downloaded to '$file' from '$PUB_URL'"
fi
else
echoErr "ERROR: Specified file CID '$cid' is NOT valid"
return 1
fi
}
# Allows to safely download file from external resources by hash verification or cosign file signature
# In the case where cosign verification is used the "<url>.sig" URL must exist
# safeWget <file> <url> <hash>
# safeWget <file> <url> <pubkey-path>
# safeWget <file> <url> <hash>,<hash>,<hash>...
# safeWget <file> <url> <CID>
function safeWget() {
local OUT_PATH="$1"
local FILE_URL="$2"
local EXPECTED_HASH="$3"
local timeout=""
local sig_timeout=""
local waitretry=""
local tries=""
getArgs --gargs_throw=false --gargs_verbose=false "$1" "$2" "$3" "$4" "$5" "$6" "$7"
(! $(isNaturalNumber "$timeout")) && timeout=900
(! $(isNaturalNumber "$sig_timeout")) && sig_timeout=30
(! $(isNaturalNumber "$waitretry")) && waitretry=1
(! $(isNaturalNumber "$tries")) && tries=2
# we need to use MD5 for TMP files to ensure that we download the file again if URL changes
local OUT_NAME=$(echo "$OUT_PATH" | md5)
local TMP_DIR=/tmp/downloads
local TMP_PATH="$TMP_DIR/${OUT_NAME}"
local PUB_URL=""
local SIG_URL="${FILE_URL}.sig"
local TMP_PATH_SIG="$TMP_DIR/${OUT_NAME}.sig"
local TMP_PATH_PUB="$TMP_DIR/${OUT_NAME}.pub"
mkdir -p "$TMP_DIR"
rm -fv "$TMP_PATH_SIG" "$TMP_PATH_PUB"
local FILE_HASH=$(sha256 $TMP_PATH)
local EXPECTED_HASH_ARR=($(echo "$EXPECTED_HASH" | tr ',' '\n'))
local EXPECTED_HASH_FIRST="${EXPECTED_HASH_ARR[0]}"
local COSIGN_PUB_KEY=""
local PUB_URL=""
local DOWNLOAD_SUCCESS="false"
if (! $(isCommand cosign)) ; then
echoErr "ERROR: Cosign tool is not installed, please install version v2.0.0 or later."
return 1
fi
if (! $(isCommand curl)) ; then
echoINFO "INFO: Curl not installed. Installing..."
apt-get install curl -y || ( echoErr "Failed to install curl, missing dependency" && exit 1 )
fi
if (! $(isSHA256 "$EXPECTED_HASH_FIRST")) ; then
if ($(isCID "$EXPECTED_HASH_FIRST")) ; then
echoInfo "INFO: Detected IPFS CID, searching available gatewys..."
COSIGN_PUB_KEY="$TMP_PATH_PUB"
ipfsGet --file="$COSIGN_PUB_KEY" --cid="$EXPECTED_HASH_FIRST" --timeout="$sig_timeout"
if ($(isFileEmpty $COSIGN_PUB_KEY)); then
echoErr "ERROR: Failed to locate or download public key file '$EXPECTED_HASH_FIRST' from any public IPFS gateway :("
return 1
fi
elif (! $(isFileEmpty "$EXPECTED_HASH_FIRST")) ; then
echoInfo "INFO: Detected public key file"
COSIGN_PUB_KEY="$EXPECTED_HASH_FIRST"
fi
if (! $(isFileEmpty $COSIGN_PUB_KEY)) || ($(urlExists "$COSIGN_PUB_KEY")) ; then
echoWarn "WARNING: Attempting to fetch signature file..."
wget --timeout="$sig_timeout" --tries="$tries" --waitretry=1 --user-agent="$UBUNTU_AGENT" "$SIG_URL" -O $TMP_PATH_SIG
else
echoErr "ERROR: Public key was not found in '$COSIGN_PUB_KEY'"
return 1
fi
else
echoInfo "INFO: One of the following checksums will be used to verify file integrity: '${EXPECTED_HASH_ARR[*]}'"
fi
local COSIGN_VERIFIED="false"
if ( (! $(isFileEmpty $COSIGN_PUB_KEY)) || ($(urlExists "${COSIGN_PUB_KEY}" 1)) ) && (! $(isFileEmpty $TMP_PATH)) ; then
echoInfo "INFO: Using cosign to verify temporary file integrity..."
COSIGN_VERIFIED="true"
cosign verify-blob --key="$COSIGN_PUB_KEY" --signature="$TMP_PATH_SIG" "$TMP_PATH" --insecure-ignore-tlog --insecure-ignore-sct || \
cosign verify-blob --key="$COSIGN_PUB_KEY" --signature="$TMP_PATH_SIG" "$TMP_PATH" || COSIGN_VERIFIED="false"
if [ "$COSIGN_VERIFIED" == "true" ] ; then
echoInfo "INFO: Cosign successfully verified integrity of an already existing temporary file"
EXPECTED_HASH="$FILE_HASH"
else
echoInfo "INFO: Cosign failed to verify temporary file integrity"
EXPECTED_HASH=""
fi
fi
EXPECTED_HASH_ARR=($(echo "$EXPECTED_HASH" | tr ',' '\n'))
local HASH_MATCH="false"
for hash in "${EXPECTED_HASH_ARR[@]}" ; do
local sanitized=$(delWhitespaces "$hash" | sed 's/^0x//')
if [ "$FILE_HASH" == "$sanitized" ] && ($(isSHA256 "$sanitized")); then
HASH_MATCH="true"
echoInfo "INFO: No need to download, file with the hash '$FILE_HASH' was already found in the '$TMP_DIR' directory"
[ "$TMP_PATH" != "$OUT_PATH" ] && cp -fv $TMP_PATH $OUT_PATH
break
fi
done
if [ "$HASH_MATCH" == "false" ] ; then
rm -fv $OUT_PATH
wget --timeout="$timeout" --tries="$tries" --waitretry=1 --user-agent="$UBUNTU_AGENT" "$FILE_URL" -O $TMP_PATH
[ "$TMP_PATH" != "$OUT_PATH" ] && cp -fv $TMP_PATH $OUT_PATH
FILE_HASH=$(sha256 $OUT_PATH)
fi
COSIGN_VERIFIED="false"
if [ "$HASH_MATCH" == "false" ] && (! $(isFileEmpty $COSIGN_PUB_KEY)) && (! $(isFileEmpty $OUT_PATH)) ; then
echoInfo "INFO: Using cosign to verify final file integrity..."
COSIGN_VERIFIED="true"
cosign verify-blob --key="$COSIGN_PUB_KEY" --signature="$TMP_PATH_SIG" "$OUT_PATH" --insecure-ignore-tlog --insecure-ignore-sct || \
cosign verify-blob --key="$COSIGN_PUB_KEY" --signature="$TMP_PATH_SIG" "$OUT_PATH" || COSIGN_VERIFIED="false"
if [ "$COSIGN_VERIFIED" == "true" ] ; then
echoInfo "INFO: Cosign successfully verified integrity of downloaded file"
EXPECTED_HASH="$FILE_HASH"
else
echoInfo "INFO: Cosign failed to verify integrity of downloaded file"
EXPECTED_HASH="cosign"
fi
fi
EXPECTED_HASH_ARR=($(echo "$EXPECTED_HASH" | tr ',' '\n'))
HASH_MATCH="false"
for hash in "${EXPECTED_HASH_ARR[@]}" ; do
local sanitized=$(delWhitespaces "$hash" | sed 's/^0x//')
if [ "$FILE_HASH" == "$sanitized" ] && ($(isSHA256 "$sanitized")) ; then
HASH_MATCH="true"
break
fi
done
if ($(isFileEmpty $OUT_PATH)) ; then
echoErr "ERROR: Failed download from '$FILE_URL', file is exmpty or was NOT found!"
return 1
elif [ "$HASH_MATCH" != "true" ] ; then
rm -fv $OUT_PATH || echoErr "ERROR: Failed to delete '$OUT_PATH'"
echoErr "ERROR: Safe download filed: '$FILE_URL' -x-> '$OUT_PATH'"
echoErr "ERROR: Expected hash (one of): '${EXPECTED_HASH_ARR[*]}', but got '$FILE_HASH'"
return 1
else
echoInfo "INFO: Safe download suceeded: '$FILE_URL' ---> '$(realpath $OUT_PATH)'"
fi
}
function getCpuCores() {
local CORES=$(cat /proc/cpuinfo | grep processor | wc -l 2> /dev/null || echo "0")
($(isNaturalNumber "$CORES")) && echo $CORES || echo "0"
}
function getRamTotal() {
local MEMORY=$(grep MemTotal /proc/meminfo | awk '{print $2}' || echo "0")
($(isNaturalNumber "$MEMORY")) && echo $MEMORY || echo "0"
}
# allowed modes: 'default', 'short', 'long'
function getArch() {
declare -l mode="$1"
declare -l arch="$(uname -m)"
if [[ "$arch" == *"arm"* ]] || [[ "$arch" == *"aarch"* ]] ; then
echo "arm64"
elif [[ "$arch" == *"x64"* ]] || [[ "$arch" == *"x86_64"* ]] || [[ "$arch" == *"amd64"* ]] || [[ "$arch" == *"amd"* ]] ; then
if [ "$mode" == "short" ] ; then
echo "x64"
else
echo "amd64"
fi
else
echo "$arch"
fi
}
function getArchX() {
echo $(bu getArch 'short')
}
function getPlatform() {
declare -l platform="$(uname)"
echo "$(bu delWhitespaces "$platform")"
}
function tryMkDir {
for kg_var in "$@" ; do
kg_var=$(echo "$kg_var" | tr -d '\011\012\013\014\015\040' 2>/dev/null || echo -n "")
[ -z "$kg_var" ] && continue
[ "$(bu toLower "$kg_var")" == "-v" ] && continue
if [ -f "$kg_var" ] ; then
if [ "$(bu toLower "$1")" == "-v" ] ; then
rm -f "$kg_var" 2> /dev/null || :
[ ! -f "$kg_var" ] && echo "removed file '$kg_var'" || echo "failed to remove file '$kg_var'"
else
rm -f 2> /dev/null || :
fi
fi
if [ "$(bu toLower "$1")" == "-v" ] ; then
[ ! -d "$kg_var" ] && mkdir -p "$var" 2> /dev/null || :
[ -d "$kg_var" ] && echo "created directory '$kg_var'" || echo "failed to create direcotry '$kg_var'"
elif [ ! -d "$kg_var" ] ; then
mkdir -p "$kg_var" 2> /dev/null || :
fi
done
}
function tryCat {
if ($(isFileEmpty $1)) ; then
echo -ne "$2"
else
cat $1 2>/dev/null || echo -ne "$2"
fi
}
function isDirEmpty() {
if [ -z "$1" ] || [ ! -d "$1" ] || [ -z "$(ls -A "$1")" ] ; then echo "true" ; else
echo "false"
fi
}
function isSimpleJsonObjOrArr() {
if ($(isNullOrEmpty "$1")) ; then echo "false"
else
local kg_HEADS=$(echo "$1" | head -c 8)
local kg_TAILS=$(echo "$1" | tail -c 8)
local kg_STR=$(echo "${kg_HEADS}${kg_TAILS}" | tr -d '\n' | tr -d '\r' | tr -d '\a' | tr -d '\t' | tr -d ' ')
if ($(isNullOrEmpty "$kg_STR")) ; then echo "false"
elif [[ "$kg_STR" =~ ^\{.*\}$ ]] ; then echo "true"
elif [[ "$kg_STR" =~ ^\[.*\]$ ]] ; then echo "true"
else echo "false"; fi
fi
}
function isSimpleJsonObjOrArrFile() {
if [ ! -f "$1" ] ; then echo "false"
else
local kg_HEADS=$(head -c 8 $1 2>/dev/null || echo -ne "")
local kg_TAILS=$(tail -c 8 $1 2>/dev/null || echo -ne "")
echo $(isSimpleJsonObjOrArr "${kg_HEADS}${kg_TAILS}")
fi
}
# Accepted flags (as params 4,5,6,7): sort_keys (bool), ensure_ascii (bool), encoding (str), indent (bool)
function jsonParse() {
local QUERY=""
local FIN=""
local FOUT=""
local INPUT=""
local sort_keys="false"
local ensure_ascii="false"
local encoding="utf8"
local indent="false"
[ ! -z "${4}${5}${6}${7}" ] && getArgs --gargs_throw=false --gargs_verbose=false "$4" "$5" "$6" "$7"
[ -z "$sort_keys" ] && sort_keys="false" || sort_keys="$(toLower "$sort_keys")"
[ -z "$ensure_ascii" ] && ensure_ascii="false" || ensure_ascii="$(toLower "$ensure_ascii")"
[ -z "$encoding" ] && ensure_ascii="utf8"
[ -z "$indent" ] && indent="false" || ensure_ascii="$(toLower "$ensure_ascii")"
sort_keys="$(toCapital "$sort_keys")"
ensure_ascii="$(toCapital "$ensure_ascii")"
[ "$indent" == "true" ] && indent=",indent=4" || indent=""
INPUT=$(echo $1 | xargs 2> /dev/null 2> /dev/null || echo -n "")
[ ! -z "$2" ] && FIN=$(realpath $2 2> /dev/null || echo -n "")
[ ! -z "$3" ] && FOUT=$(realpath $3 2> /dev/null || echo -n "")
if [ ! -z "$INPUT" ] ; then
for k in ${INPUT//./ } ; do
k=$(echo $k | xargs 2> /dev/null || echo -n "") && [ -z "$k" ] && continue
[[ "$k" =~ ^\[.*\]$ ]] && QUERY="${QUERY}${k}" && continue
($(isNaturalNumber "$k")) && QUERY="${QUERY}[$k]" || QUERY="${QUERY}[\"$k\"]"
done
fi
if [ ! -z "$FIN" ] ; then
if [ ! -z "$FOUT" ] ; then
[ "$FIN" != "$FOUT" ] && rm -f "$FOUT" || :