Repository navigation
Expand file tree
/
Copy pathxlib
More file actions
executable file
·2106 lines (1928 loc) · 71.8 KB
/
Copy pathxlib
File metadata and controls
executable file
·2106 lines (1928 loc) · 71.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
#!/bin/bash
# Copyright 2017 bin jin
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Resolve the real script directory, follow symlink
__script_dir () {
[ "$__SELF_DIR" ] && { printf "%s" "$__SELF_DIR"; return; }
local src=$0 dir;
while [ -L "$src" ]; do
dir=$(cd "$(dirname "$src")" && pwd);
src=$(readlink "$src");
case $src in /*) :;; *) src="$dir/$src";; esac
done
cd "$(dirname "$src")" && pwd
}
__SELF_DIR=$(__script_dir)
# Framework:
#
# A function whose name conforms to the specification gets:
# External invocation.
# Error handling.
# Help information.
# The function list.
# Shell completion.
#
# The annotation is both the help text and the completion source; keep it next to the code:
# A [###] at the line start is for the command; an indented [###] is for the case pattern below it.
#
# For example:
# ### [brief_introduction]
# ### Usage: [function_name] [OPTION]... [OPERAND]...
# [script_name]_[function_name](){
# [function_body]
# case $1 in
# ### -o, --option=FILE [description]
# --option|-o)
# [function_body]
# ;;
# ### OPERAND=FILE [description]
# *)
# [function_body]
# ;;
# esac
# # exit and display [error_description]
# exit 1; # [error_description]
# }
#
# The metavariable names the completion source:
# FILE IMAGE DIRECTORY DEVICE PATH HOST ADDRESS MAC ALIAS HOSTIP SHELL KIND
# {a|b} is an enumeration, e.g., {yes|no}
# The kinds of this host are declared by __COMP_KINDS, __comp_kind_host and
# __comp_value_host; the generic engine lives in comp.xlib.
#
# A platform tag at the end of an annotation line marks it as platform specific:
# [macOS] or [Linux]; the tag is shown in help and skipped by completion
# on the other platform.
#
# [###] is reserved for annotation; any other comment must use [#]:
# Use [comp --check] to check the annotations.
### Print version and exit
### Usage: version
_xlib_version () {
printf "0.26.9.26\n" >&2;
return 0
}
### Control the cursor
### Usage: cur [OPTION]
_xlib_cur () {
case $1 in
### -, --hide hide the cursor
--hide|-)
printf '\033[?25l'
# trap 'printf "\033[?25h"; exit' INT; # Show the cursor after Ctrl-C.
;;
### +, --show show the cursor
--show|+)
printf '\033[?25h'
;;
"")
local p=;
printf '\e[6n';
read -sdR p;
printf "${p#*[}\n"
;;
*)
exit 1; # Invalid option.
;;
esac
}
### Create or convert a package file [macOS]
### Usage: pkg [OPTION]... [PATH]
_xlib_pkg () {
[[ $OSTYPE == darwin* ]] || exit 1; # Only macOS (OS X) is supported.
local tmp;
case $1 in
### -n, --dmg=DIRECTORY create a DMG from a DIRECTORY
--dmg|-n)
shift;
[ -d "$1" ] || exit 1; # Target directory not found.
# Trim: # linux:${1:0:-1} -> darwin:${1:0:${#1}-1}
[ "${1:0-1}" == "/" ] && tmp="${1:0:${#1}-1}" || tmp="$1";
tmp=${tmp##*/};
hdiutil create -srcfolder "$1" -skipunreadable -format UDZO "$tmp.dmg" || return 1
;;
### -t, --verify=FILE verify a DMG FILE
--verify|-t)
shift;
[ "${1##*.}" == "dmg" -o "${1##*.}" == "DMG" ] || exit 1; # Invalid format.
hdiutil verify "$1"
;;
### -di, --dmg2iso=FILE convert a DMG FILE to ISO
--dmg2iso|-di)
shift;
[ -f "$1" ] || exit 1; # DMG file not found.
[ "${1##*.}" == "dmg" -o "${1##*.}" == "DMG" ] || exit 1; # Not a DMG file.
tmp=${1##*/};
tmp=${tmp%.*};
hdiutil convert "$1" -format UDTO -o "$tmp.iso";
;;
### -id, --iso2dmg=FILE convert an ISO FILE to DMG
--iso2dmg|-id)
shift;
[ -f "$1" ] || exit 1; # ISO file not found.
[ "${1##*.}" == "iso" -o "${1##*.}" == "ISO" ] || exit 1; # Not an ISO file.
tmp=${1##*/};
tmp=${tmp%.*};
hdiutil convert "$1" -format UDRW -o "$tmp.dmg";
;;
### -u, --udf=DIRECTORY create an ISO from a DIRECTORY
--udf|-u)
shift;
[[ $OSTYPE == darwin* ]] || exit 1; # Only macOS (OS X) is supported.
[ -d "$1" ] || exit 1; # Directory not found.
# hdiutil makehybrid -iso -joliet -o win8.iso win8.cdr
hdiutil makehybrid -udf -udf-version 1.02 -o "$1.iso" "$1";
return 0
;;
### -w, --dd=IMAGE|DEVICE write IMAGE to DEVICE, e.g., /dev/disk2
--dd|-w)
shift;
# caller 0;
[ -f "$1" ] || exit 1; # Image file not found.
local target i j k l;
[ "${2:0:9}" == "/dev/disk" ] && {
target=$2
} || {
# Cut the mount info.
while read i j k; do
[ "${k%% (*}" == "$2" ] && target=$i
done < <(mount)
}
# Trim the slice suffix.
[[ $target == *disk[0-9]s[0-9] ]] && target=${target%s*};
case ${1##*.} in
img)
diskutil unmountDisk $target >/dev/null || exit 1; # Cannot unmount this disk.
sudo dd if="$1" of=$target bs=4m || exit 1; # The dd command failed.
;;
iso)
diskutil unmountDisk $target >/dev/null || exit 1; # Cannot unmount this disk.
hdiutil convert "$1" -format UDRW -o "${1%.*}.dmg" >/dev/null;
sudo dd if="${1%.*}.dmg" of=$target bs=4m || exit 1; # The dd command failed.
rm "${1%.*}.dmg";
# sudo dd if="${1%.*}.dmg" of=$target bs=4m & while killall -USR1 dd; do
# sleep 10;
# done | _xlib_prefix "%F %T, "
;;
gz)
which gzcat >/dev/null 2>&1 || exit 1; # The gzcat command was not found.
diskutil unmountDisk $target >/dev/null || exit 1; # Cannot unmount this disk.
gzcat "$1" | sudo dd of=$target bs=4m || exit 1; # The dd command failed.
;;
xz)
which xzcat >/dev/null 2>&1 || exit 1; # The xzcat command was not found; try 'brew install xz'.
diskutil unmountDisk $target >/dev/null || exit 1; # Cannot unmount this disk.
xzcat "$1" | sudo dd of=$target bs=4m || exit 1; # The dd command failed.
;;
*)
exit 1; # Format not supported.
;;
esac
sync;
diskutil eject $target >/dev/null
return 0
;;
### -g, --get[=NUMBER] get an APK file from the AppStore; NUMBER is the countdown in minutes
--get|-g)
[[ ${OSTYPE/darwin/} > 24.9 ]] && {
printf "\033[31mError: OS version too new.\033[0m\n" >&2;
return 1
}
__get_pkg $2
;;
*)
exit 1; # Invalid option.
;;
esac
}
# Get an APK file from the AppStore.
__get_pkg () {
[[ $OSTYPE == darwin* ]] || exit 1; # Only macOS (OS X) is supported.
# sudo chown -R $USER:`id -gn $USER` /private/var/folders
# sudo chmod -R 755 /private/var/folders
[ `ps -ef | grep -c "${0##*/}.*pkg.*-g"` -gt 3 ] && exit 1; # The pkg command is already running.
# Override the pkg map: pkg[$serial_number]="$path".
function ___get_pkg_serial_number () {
local k v;
while read k v; do
# Put it in the map.
[ "$v" ] && pkg[$k]="$v";
done < <(find "$1" -type f -iname "*.pkg" -exec ls -i {} \; 2>/dev/null); # *.tmp *.pkg
return 0
};
# Hash the file and move it to ~/Downloads.
function ___get_pkg_complete () {
[ -f "$1" ] || return 1;
local name=${1##*/};
name=${name#*_};
name=${name%.*};
{
printf "NAME: ${1##*/}\n";
printf "SIZE: ";
du -h "$1" | awk '{print $1}'
printf "TIME: ";
_xlib_str --dhms $(($(date +%s) - $sec_on));
_xlib_hash "$1"
mv "$1" ~/Downloads 2>/dev/null || {
cp "$1" ~/Downloads && printf "\033[31m$1 still exist\033[0m\n"
}
} | awk -v name="${name:0:8}, " '{print name $0; fflush(stdout)}'
};
local i anchor count_cache=0 pkg=() tmp=/private/var/tmp store_agent countdown=$((${1-1} * 60 * 5)) sec_on=$(date +%s);
{
printf -v store_agent /private/var/folders/*/*/C/com.apple.appstoreagent/com.apple.appstore;
printf "Will listen \033[4m%s\033[0m sec.\n" $(($countdown / 5));
# Register a hard link from /private/var/tmp.
___get_pkg_serial_number "$store_agent";
# Infinite loop.
while :; do
# Exit when all downloads are complete.
[ $countdown -lt 0 -a ${#pkg[@]} == 0 ] && {
printf "Exit.\n";
break
};
[ $((countdown -= 1)) == 0 ] && printf "Listening \033[4mstop\033[0m.\n";
# Search for the downloaded package.
___get_pkg_serial_number "$store_agent";
# Iterate over the package array.
[ ${#pkg[@]} -gt 0 ] && for i in ${!pkg[@]}; do
# Already complete.
[ "${pkg[$i]%/*}" == "$tmp" ] && {
___get_pkg_complete "${pkg[$i]}" &
unset pkg[$i];
continue
};
anchor=$tmp/${i}_${pkg[$i]##*/}; # Anchor file path.
# Add a hard link.
[ -f "$anchor" ] || {
ln "${pkg[$i]}" "$anchor" && printf "Add \033[4m${pkg[i]##*/}\033[0m.\n";
};
# The download is complete.
[ -f "${pkg[$i]}" ] || {
unset pkg[$i];
___get_pkg_complete "$anchor" &
};
done;
[ ${count_cache} != ${#pkg[@]} ] && {
printf "Count: ${#pkg[@]}\n";
count_cache=${#pkg[@]}
};
sleep 0.2
done;
} | _xlib_prefix "%F %T, GPKG, "
# Wait for all threads to finish.
wait
}
### Wake on LAN
### Usage: wol [OPTION]... TARGET
_xlib_wol () {
[ "$1" ] || exit 1; # MAC address is empty.
source "$(__script_dir)/bash.xlib";
# Load the [hosts] ini config into map0.
__load_ini hosts;
local i j mac_addr broadcast sub seen mac_arr=();
case $1 in
### -b, --broadcast=ADDRESS|ALIAS broadcast ADDRESS for all targets
--broadcast|-b)
shift;
# Resolve the broadcast address from an IPv4 address or host alias.
for i in `__wol_addr "$1"`; do
_xlib_ip --test "$i" && { broadcast=$i; break; }
done
[ "$broadcast" ] || exit 1; # Cannot resolve the broadcast IPv4 address.
shift
;;
### TARGET=ALIAS|HOSTIP MAC address, hosts alias or IPv4 address
*)
# Default broadcast addresses: the subnet of every default route of a
# physical interface. A machine may hold more than one, and a virtual
# adapter (a proxy TUN, a VPN) holds a route whose subnet cannot reach
# the LAN, so only the physical routes count; the order is not
# significant.
broadcast=; seen=;
for i in `__route_gateway`; do
sub="${i%.*}";
case " $seen " in *" $sub "*) continue;; esac
seen="$seen $sub";
broadcast="$broadcast$sub.255 ";
done
[ "$broadcast" ] || exit 1; # Cannot resolve the broadcast IPv4 address.
;;
esac
[ "$1" ] || exit 1; # MAC address is empty.
# Resolve all MAC addresses from a MAC address, host alias or IPv4 address.
for i in "$@"; do
mac_addr=;
for j in `__wol_addr "$i"`; do
[[ ${j//-/:} == *:*:*:*:*:* ]] || continue;
mac_addr=true;
mac_arr[${#mac_arr[@]}]=$j;
done
[ "$mac_addr" ] || exit 1; # Cannot resolve the MAC address.
done
# Wake each MAC address on every broadcast address.
for i in ${mac_arr[@]}; do
for j in $broadcast; do
__wol "$i" "$j";
done
done
}
# Print MAC addresses and IPv4 addresses for the [hosts] ini, from a MAC address,
# host alias or IPv4 address. Read the ini config from HOME or the script path,
# and reverse lookup in /etc/hosts.
# Usage: __wol_addr [STRING]
__wol_addr () {
[ "$1" ] || return 1;
local i j k line;
# By MAC address or host alias.
line=`_map --get "$1"`;
line=${line:-$1};
# By IPv4 address.
if _xlib_ip --test "$1"; then
# Reverse lookup the host alias in map0.
if [ "$line" == "$1" ]; then
_map --keys;
for i in ${MAP2ARRAY[@]}; do
j=`_map --get "$i"`;
for k in ${j//|/ }; do
[ "$k" == "$1" ] && { line=$j; break 2; }
done
done
fi
# Reverse lookup the host name in /etc/hosts, which the [hosts] command updates.
if [ "$line" == "$1" ]; then
for i in `awk -v ip="$1" '$1 == ip {for (n = 2; n <= NF; n++) print $n}' /etc/hosts`; do
j=`_map --get "$i"`;
[ "$j" ] && { line=$j; break; }
done
fi
fi
# Print the MAC address and IPv4 address.
local addr IFS=$IFS"|";
addr=($line);
IFS=${IFS%|};
for i in ${addr[@]}; do
_xlib_ip --test "$i" && { printf "%s\n" "$i"; continue; }
[[ ${i//-/:} == *:*:*:*:*:* ]] && printf "%s\n" "$i"
done
return 0
}
__wol () {
# The magic packet is built with the brace expansion of bash, and this script
# always runs on bash whatever [SHELL] says, so any perl found is usable and
# is the cheapest sender; python3 and python2 are the fallbacks.
if which perl >/dev/null 2>&1; then
printf $(
{
printf 'f%.0s' {1..12};
printf "${1//[:-]/}%.0s" {1..16};
} | sed 's/../\\x&/g'
) | perl -ne 'use Socket; socket(S, AF_INET, SOCK_DGRAM, getprotobyname("udp")); setsockopt(S, SOL_SOCKET, SO_BROADCAST, 1); send(S, $_, 0, pack_sockaddr_in(9, inet_aton("'"$2"'"))); close S' || \
exit 1; # The perl command failed.
elif which python3 >/dev/null 2>&1; then
# 'decode("hex")' of python2 became 'bytes.fromhex' in python3.
python3 -c 'import socket; S=socket.socket(socket.AF_INET, socket.SOCK_DGRAM); S.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1); S.sendto(bytes.fromhex("".join(["F" * 12, "'"$1"'".replace(":", "").replace("-", "") * 16])), ("'"$2"'", 9))' || \
exit 1; # The python3 command failed.
elif which python >/dev/null 2>&1; then
python -c 'import socket; S=socket.socket(socket.AF_INET, socket.SOCK_DGRAM); S.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1); S.sendto("".join(["F" * 12, "'"$1"'".replace(":", "").replace("-", "") * 16]).decode("hex"), ("'"$2"'", 9))' || \
exit 1; # The python command failed.
else
exit 1; # Not supported.
fi
}
### Remote tools
### Usage: remote [OPTION]... [ARG]...
_xlib_remote () {
case $1 in
### -ed25519=HOST copy the ed25519 public key to HOST; an optional ALIAS suffix may be given
-ed25519)
shift;
__remote_ed25519 "$@"
;;
### -scp=PASSWORD COMMAND... copy files over scp with PASSWORD
-scp)
shift;
__remote_auto_scp "$@"
;;
### -tar=PATH transfer PATH by tar, the first ARG is a tar option
-tar)
shift;
__remote_tar "$@"
;;
*)
exit 1; # Invalid option.
;;
esac
}
# For _xlib_remote.
__remote_ed25519 () {
[ "$1" ] || exit 1; # First argument is empty.
local ed25519_pub;
[ -s ~/.ssh/id_ed25519$2.pub ] || ssh-keygen -t ed25519 -P "" -f ~/.ssh/id_ed25519$2;
printf %s 'mkdir ~/.ssh 2>/dev/null;
printf %s "'`cat ~/.ssh/id_ed25519$2.pub 2>/dev/null`'" >> ~/.ssh/authorized_keys;
chmod 600 ~/.ssh/authorized_keys;
chmod 700 ~/.ssh
' | ssh $1 bash || exit 1; # Unknown error.
local host=${1#*@} user;
[ "$host" == "$1" ] && user=${1%@*} || user=$USER;
printf %s "Host $host
HostName $host
Port 22
User $user
IdentityFile ~/.ssh/id_ed25519$2
"
return 0
}
# For _xlib_remote.
__remote_auto_scp () {
local password;
which expect >/dev/null 2>&1 || exit 1; # The expect command was not found.
password=$1;
shift;
expect <<-TCL
set timeout 150
spawn scp $*
expect {
timeout { exit 2 }
"*yes/no" { send "yes\r"; exp_continue }
"*assword:" { send "$password\r" }
}
expect {
timeout { exit 2 }
"*denied*" { exit 3 }
"No such" { exit 4 }
#### "100%" { exit 0 }
}
expect eof
TCL
case $? in
1)
exit 1; # Expect error.
;;
2)
exit 1; # Timed out.
;;
3)
exit 1; # Password error.
;;
4)
exit 1; # File not found.
;;
*)
exit 1; # Unknown error.
;;
esac
}
__remote_tar () {
[ "$1" ] || exit 1; # Target URL is empty.
[ "$2" ] || exit 1; # Source URL is empty.
local option="$1" target_host target_dir source_host source_dir;
shift;
target_dir="${1#*:}";
[ "$target_dir" == "$1" ] || target_host=${1%%:*};
# ${target_dir:(-1)} == ${target_dir:0-1}
[ "${target_dir:0-1}" == "/" ] && target_dir="${target_dir:0:${#target_dir}-1}"
source_dir="${2#*:}";
[ "$source_dir" == "$2" ] || source_host=${2%%:*};
[ "${source_dir:0-1}" == "/" ] && source_dir="${source_dir:0:${#source_dir}-1}"
# echo $target_host, $target_dir, $source_host, $source_dir
# return 0
function ___tar_c () {
{
[ "${option/P/}" == "$option" ] && \
printf %s 'cd "'"${2%/*}"'" >/dev/null && tar '$option' - "'"${2##*/}"'"' || \
printf %s 'tar '$option' - "'"$2"'"'
} | ssh $1 bash
};
function ___tar_x () {
[ "${option/P/}" == "$option" ] && {
ssh $1 'cd "'"$2"'" >/dev/null && tar '$option' -'
} || ssh $1 'tar '$option' - '
};
function ___tar_cat_i () {
ssh $1 'cat > "'"$2"'"'
};
function ___tar_cat_o () {
ssh $1 'cat "'"$2"'"'
};
case $option in
*c*)
if [ "$target_host" -a "$source_host" ]; then
# Both sides are remote.
___tar_c $source_host "${source_dir}" | ___tar_cat_i $target_host "$target_dir"
elif [ "$target_host" ]; then
# Local to remote.
[ -d "$source_dir" ] || exit 1; # source path not found.
{
[ "${option/P/}" == "$option" ] && {
cd "${source_dir%/*}" >/dev/null && tar $option - "${source_dir##*/}"
cd "$OLDPWD"
:
} || tar $option - "${source_dir}"
} | rcat $target_host "$target_dir";
else
# Remote to local.
___tar_c $source_host "$source_dir" > "$target_dir";
fi
;;
*x*)
if [ "$target_host" -a "$source_host" ]; then
# Both sides are remote.
___tar_cat_o $source_host "${source_dir}" | ___tar_x $target_host "$target_dir"
elif [ "$target_host" ]; then
# Local to remote.
[ -f "$source_dir" ] || exit 1; # source file not found.
cat "$source_dir" | ___tar_x $target_host "$target_dir"
else
# Remote to local.
cd "$target_dir";
___tar_cat_o $source_host "$source_dir" | tar $option -;
cd "$OLDPWD"
fi
;;
*)
exit 1; # Invalid option.
;;
esac
return 0
}
### Operating system settings [macOS]
### Usage: oset [OPTION]... [ARG]...
_xlib_oset () {
[[ $OSTYPE == darwin* ]] || exit 1; # Only macOS (OS X) is supported.
case $1 in
### -v, --version print the OS version
--version|-v)
which sw_vers >/dev/null 2>&1 && {
sw_vers | awk '{if(/ProductVersion/) {printf $2}; if(/BuildVersion/) print "." $2}';
:
} || system_profiler SPSoftwareDataType | \
awk '/System Version/{gsub(/[()]/, "", $5); print $4 "." $5}'
;;
### -a, --allow allow installation of all apps
--allow|-a)
sudo spctl --master-disable;
;;
### -aa, --allow-app=FILE allow running the app bundle FILE
--allow-app|-aa)
shift;
[ -e "$1" ] || exit 1; # App bundle not set or not found.
sudo spctl --master-disable;
sudo xattr -r -d com.apple.quarantine "$1"
;;
### -, --hidden={yes|no} show or hide private files and directories
--hidden|-)
shift;
[ "$1" == "yes" -o "$1" == "no" ] || exit 1; # The value must be 'yes' or 'no'.
defaults write com.apple.finder AppleShowAllFiles $1;
;;
### -rl, --re-launch reset LaunchPad
--re-launch|-rl)
defaults write com.apple.dock ResetLaunchPad -bool true;
killall Dock
;;
### -sl, --set-launch=NUMBER set the LaunchPad ROWS and COLUMNS
--set-launch|-sl)
shift;
if [ "$2" ]; then
defaults write com.apple.dock springboard-rows -int $1
defaults write com.apple.dock springboard-columns -int $2
killall Dock
elif [ "$1" ]; then
exit 1; # Columns not set.
else
defaults write com.apple.dock springboard-rows Default
defaults write com.apple.dock springboard-columns Default
killall Dock
fi
;;
### -u, --uuid[=USER] print the UUID of USER, default is the current user
--uuid|-u)
shift;
[ "$1" ] || set "" $USER;
dsmemberutil getuuid -U $1
;;
### -s, --sid[=USER] print the SID of USER, default is the current user
--sid|-s)
shift;
[ "$1" ] || set "" $USER;
dsmemberutil getsid -U $1
;;
### -l, --lock-screen lock the screen
--lock-screen|-l)
# Ctrl + Command + Q
/System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -suspend
;;
### --ms, --mobile-sync open the MobileSync backup DIRECTORY
--mobile-sync|--ms)
open ~/Library/Application\ Support/MobileSync/Backup
;;
### --logout log out
--logout)
# killall -u $USER;
# kill -9 `ps -Axjc | awk /loginwindow/'{print $2}'`;
# # System Preferences -> Universal Access -> Enable access for assistive devices
# echo a | sudo tee /var/db/.AccessibilityAPIEnabled
# launchctl bootout user/$(id -u $USER)
printf 'tell application "System Events"
log out
end tell
' | osascript
;;
### --notify=STRING display a notification
--notify)
shift;
if [ "$3" ]; then
osascript -e 'display notification "'"$1"'" with title "'"$2"'" subtitle "'"$3"'"'
elif [ "$2" ]; then
osascript -e 'display notification "'"$1"'" with title "'"$2"'"'
else
osascript -e 'display notification "'"$1"'" with title "Hi"'
fi
;;
### --button-wait=STRING display a dialog with a Yes button and wait
--button-wait)
shift;
osascript -e 'display dialog "'"$1"'" buttons "Yes" with icon note'
;;
### --button-choose=STRING display a dialog
--button-choose)
shift;
osascript -e 'display dialog "'"$1"'"'
;;
### --set-time=STRING set the system time
--set-time)
shift;
if [ "$1" ]; then
date +%m%d%H%M%Y.%S
else
date $1
fi
;;
# Screenshots
# defaults write com.apple.screencapture location $1
# DiskUtil Debug
# defaults write com.apple.DiskUtility DUDebugMenuEnabled 1
# LaunchPad
# defaults write com.apple.dock ResetLaunchPad -bool true; killall Dock
# Spotlight close
# launchctl unload -w /System/Library/LaunchDaemons/com.apple.metadata.mds.plist
### --sleep put the system to sleep
--sleep)
sudo osascript -e 'tell application "Finder" to sleep'
;;
### --list-users list all users
--list-users)
dscl . -list /Users UniqueID
;;
*)
exit 1; # Invalid option.
;;
esac
}
### Certificate tools
### Usage: cert {selfsign|rsa|ed25519} [OPTION]...
_xlib_cert () {
case $1 in
### selfsign create a self-signed certificate
selfsign)
# nginx
shift;
local host email country="CN" state="BJ" city="BJ" company="ORG" section="dev" days=365;
while [ "$2" ]; do
case $1 in
### -cn, --host=HOST set the common name (CN)
--host|-cn)
# Common Name (eg, YOUR name) []: /CN ($IP / $hostname / $alias)
host="$2";
shift;
shift
;;
### -e, --email=STRING set the email address
--email|-e)
# Email Address []: /emailAddress mail@example.com
email="$2";
shift;
shift
;;
### -c, --country=STRING set the country name (C)
--country|-c)
# Country Name (2 letter code) [AU]: /C
country="$2";
shift;
shift
;;
### -st, --state=STRING set the state or province name (ST)
--state|-st)
# State or Province Name (full name) [Some-State]: /ST
state="$2";
shift;
shift
;;
### -l, --city=STRING set the locality name (L)
--city|-l)
# Locality Name (eg, city) []: /L
city="$2";
shift;
shift
;;
### -o, --company=STRING set the organization name (O)
--company|-o)
# Organization Name (eg, company) [Internet Widgits Pty Ltd]: /O
company="$2";
shift;
shift
;;
### -ou, --section=STRING set the organizational unit name (OU)
--section|-ou)
# Organizational Unit Name (eg, section) []: /OU
section="$2";
shift;
shift
;;
### --days=NUMBER set the number of days the certificate is valid
--days)
days="$2";
shift;
shift
;;
*)
exit 1; # Invalid option.
;;
esac
done
[ "$host" ] || exit 1; # Host name is empty.
[ "$email" ] || exit 1; # Email address is empty.
local SUBJECT="/C=$country/ST=$state/L=$city/O=$company/OU=$section/CN=$host/emailAddress=$email" \
SERVER_CERT="./$host/fullchain.pem" \
SERVER_KEY="./$host/privkey.pem" \
SERVER_CSR="/tmp/${host}_server.csr" \
CA_KEY="/tmp/${host}_ca-cert.pem" \
CA_CERT="./$host/ca.crt";
mkdir -p "$host";
# Create the CA.
openssl genrsa -out $CA_KEY 4096;
openssl req -new -x509 -days $days -key $CA_KEY -out $CA_CERT -subj "$SUBJECT";
# Create the server key.
openssl genrsa -out $SERVER_KEY 4096;
# Create the server CSR.
openssl req -new -key $SERVER_KEY -out $SERVER_CSR -subj "$SUBJECT";
# Self-sign the server CSR.
openssl x509 -req -days $days -in $SERVER_CSR -CA $CA_CERT -CAkey $CA_KEY -set_serial 01 -out $SERVER_CERT;
;;
### rsa[=SUFFIX] create an RSA key pair, SUFFIX is optional
rsa)
shift;
ssh-keygen -t rsa -P "" -f ~/.ssh/id_rsa$1;
;;
### ed25519[=SUFFIX] create an ed25519 key pair, SUFFIX is optional
ed25519)
shift;
ssh-keygen -t ed25519 -P "" -C "$USER@$HOSTNAME" -f ~/.ssh/id_ed25519$1;
;;
*)
exit 1; # Invalid option.
;;
esac
}
### Display device driver info [macOS]
### Usage: drv [OPTION]
_xlib_drv () {
case $1 in
### -v, --info print hardware info
--info|-v)
if [[ $OSTYPE == darwin* ]]; then
printf ";\n";
system_profiler SPHardwareDataType | \
awk -F : '{if($2 != ""){sub(/^[[:space:]]+/, "", $1); printf "; %+28s %s\n", $1 ":", $2}}'
printf ";\n\n";
else
:
fi
;;
### -l, --list list loaded kernel extensions
--list|-l)
if [[ $OSTYPE == darwin* ]]; then
# /System/Library/Extensions /Library/Extensions
kextstat
else
:
fi
;;
### -r, --refresh prune the kernel extension cache
--refresh|-r)
if [[ $OSTYPE == darwin* ]]; then
sudo kextcache -prune-staging
else
:
fi
;;
*)
exit 1; # Invalid option.
;;
esac
}
### Print MD5, SHA-1, SHA-256 and SHA-512 checksums
### Usage: hash [FILE]
_xlib_hash () {
which openssl >/dev/null 2>&1 || exit 1; # The openssl command was not found.
local h_code;
{
# 'tee' feeds all four digests from a single read of the input.
for h_code in $(
{
[ -f "$1" ] && {
cat "$1" | tee >(openssl dgst -sha1 >&2) >(openssl dgst -md5 >&2) >(openssl dgst -sha256 >&2) | openssl dgst -sha512;
:
} || tee >(openssl dgst -sha1 >&2) >(openssl dgst -md5 >&2) >(openssl dgst -sha256 >&2) | openssl dgst -sha512;
} 2>&1
); do
if [ ${#h_code} == 32 ]; then
printf "MD5: $h_code\n";
elif [ ${#h_code} == 40 ]; then
printf "SHA1: $h_code\n";
elif [ ${#h_code} == 64 ]; then
printf "SHA256: $h_code\n";
elif [ ${#h_code} == 128 ]; then
printf "SHA512: $h_code\n";
fi
done
} | sort # Make the report order deterministic.
}
### Volume info or edit [macOS]
### Usage: vol [OPTION]... [ARG]...
_xlib_vol () {
[[ $OSTYPE == darwin* ]] || exit 1; # Only macOS (OS X) is supported.
case $1 in
# --encrypts-all|-eca)
# local args;
# while read args; do
# set $args;
# [ "${2#/Volumes/}" == "$2" ] || diskutil apfs enableFileVault $1 -user disk
# done < <(__vol_list)
# ;;
# --encrypts|-ec)
# __vol_list
# ;;
### -w, --wipes=DIRECTORY wipe the free space on the volume at DIRECTORY
--wipes|-w)
shift;
[ -d "$1" ] || exit 1; # Target path not found.
diskutil secureErase freespace 3 $1
;;
### -im, --createinstallmedia=DEVICE create a bootable install media on DEVICE
--createinstallmedia|-im)
shift;
[ -d "$1" ] || exit 1; # Target device not found.
[ -d "$2" ] || set -- "$1" "/Applications/Install";
while read tmp; do
break;
done < <(find "$2"*/ -iname "createinstallmedia" 2>/dev/null);
[ -f "$tmp" ] || exit 1; # Install source not found.
[ -f "${tmp%Resources*}SharedSupport/InstallInfo.plist" ] || {
if [ -f "/macOS Install Data/InstallInfo.plist" ]; then
sudo mkdir -p "${tmp%Resources*}SharedSupport";
find "/macOS Install Data" -type f -exec sudo ln {} "${tmp%Resources*}SharedSupport" \;
# else
# exit 1; # need to run the 'install app' and exit before 'reboot'
fi
};
/usr/libexec/PlistBuddy \
-c 'Print :CFBundleDisplayName' \
-c 'Print :DTSDKName' \
-c 'Print :CFBundleShortVersionString' \
-c 'Print :DTSDKBuild' \
"${tmp%Resources*}Info.plist" | awk '{printf $0 " "};END{printf "\n"}'
# sudo "$tmp" --volume "$1" --applicationpath "${tmp%/Contents*}" --nointeraction;
sudo "$tmp" --volume "$1" --nointeraction;
touch "/Volumes/Install "*/.metadata_never_index
;;
*)
exit 1; # Invalid option.
;;
esac
}
# __vol_list () {
# local args;
# while read args; do