-
Notifications
You must be signed in to change notification settings - Fork 1
/
bootiso
executable file
·1900 lines (1804 loc) · 59.8 KB
/
bootiso
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
# shellcheck disable=SC2181
# shellcheck disable=SC2236
#
# Author: jules randolph <[email protected]> https://github.com/jsamr
# License: MIT
# Version 4.0.0-alpha.0
set -o pipefail
set -E
version="4.0.0-alpha.0"
scriptName=$(basename "$0")
bashVersion=$(echo "$BASH_VERSION" | cut -d. -f1)
if [ -z "$BASH_VERSION" ] || [ "$bashVersion" -lt 4 ]; then
echo >&2 "You need bash v4+ to run this script. Aborting..."
exit 1
fi
# program constrains definitions
typeset -ar commandDependencies=('lsblk' 'column' 'sfdisk' 'mkfs' 'blkid' 'wipefs' 'blockdev' 'grep' 'file' 'awk' 'mlabel' 'syslinux' 'rsync'
'partprobe' 'curl' 'tar' 'bc' 'wimlib-imagex' 'md5sum' 'sha1sum' 'sha256sum' 'sha512sum' 'cut')
typeset -Ar commandPackages=(
['lsblk']='util-linux'
['sfdisk']='util-linux'
['mkfs']='util-linux'
['blkid']='util-linux'
['wipefs']='util-linux'
['blockdev']='util-linux'
['column']='util-linux'
['grep']='grep'
['file']='file'
['awk']='gawk'
['mlabel']='mtools'
['syslinux']='syslinux'
['rsync']='rsync'
['partprobe']='parted'
['curl']='curl'
['tar']='tar'
['bc']='bc'
['wimlib-imagex']='wimlib'
['md5sum']='coreutils'
['sha1sum']='coreutils'
['sha256sum']='coreutils'
['sha512sum']='coreutils'
['cut']='coreutils'
)
typeset shortOptions='bydJahlMftLp'
typeset -ar supportedFS=('vfat' 'exfat' 'ntfs' 'ext2' 'ext3' 'ext4' 'f2fs')
typeset -Ar userVarsCompatibilityMatrix=(
['iso-file']='install-auto install-mount-rsync install-dd inspect probe'
['device']='install-auto install-mount-rsync install-dd format'
['type']='install-mount-rsync format'
['label']='install-mount-rsync format'
['remote-bootloader']='install-auto install-mount-rsync'
)
typeset -Ar userFlagsCompatibilityMatrix=(
['local-bootloader']='install-auto install-mount-rsync'
['assume-yes']='install-auto install-mount-rsync install-dd format'
['no-eject']='install-auto install-mount-rsync install-dd format'
['autoselect']='install-auto install-mount-rsync install-dd format'
['no-mime-check']='install-auto install-mount-rsync install-dd'
['no-hash-check']='install-auto install-mount-rsync install-dd probe inspect'
['force-hash-check']='install-auto install-mount-rsync install-dd probe inspect'
['no-usb-check']='install-auto install-mount-rsync install-dd list-usb-drives probe format'
['no-size-check']='install-auto install-mount-rsync install-dd'
)
# internal variables
typeset syslinuxLibRoot=${SYSLINUX_LIB_ROOT:-'/usr/lib/syslinux'}
typeset ticketsurl="https://github.com/jsamr/bootiso/issues"
typeset mountRoot=/mnt
typeset tempRoot=/var/tmp/bootiso
typeset cacheRoot=/var/cache/bootiso
typeset selectedPartition
typeset isoMountPoint
typeset usbMountPoint
typeset startTime
typeset endTime
typeset addSyslinuxBootloader=false
typeset syslinuxVersion
typeset -a devicesList
typeset operationSuccess
typeset expectingISOFile
typeset foundSyslinuxMbrBinary
typeset foundSyslinuxBiosFolder
typeset -A syslinuxInstall
typeset -a temporaryAssets=()
typeset -A isoInspection=(
['isHybrid']=''
['syslinuxBin']=''
['syslinuxVer']=''
['syslinuxConf']=''
['supportsEFIBoot']=''
)
typeset -A userFlags=(
# Actions
['help']=''
['version']=''
['list-usb-drives']=''
['format']=''
['install-dd']=''
['install-mr']=''
['inspect']=''
['probe']=''
# Options
['local-bootloader']=''
['assume-yes']=''
['device']=''
['no-eject']=''
['autoselect']=''
['no-mime-check']=''
['no-usb-check']=''
['no-size-check']=''
['no-hash-check']=''
['force-hash-check']=''
['no-wimsplit']=''
)
typeset -A userVars=(
['iso-file']=''
['hash-file']=''
['device']=''
['type']=''
['label']=''
['remote-bootloader']=''
)
# user defined variables
typeset selectedIsoFile # no default
typeset hashFile
typeset selectedDevice # default to prompted to user
typeset partitionLabel # default to inferred from ISO file label
typeset partitionType # default to vfat
typeset action='install-auto'
typeset selectedBootloaderVersion # default to auto
# options
typeset disableMimeCheck
typeset disableUSBCheck
typeset disableSizeCheck
typeset disableConfirmation
typeset disableHashCheck
typeset forceHashCheck
typeset disableWimsplit
typeset autoselect
typeset shouldMakePartition
typeset noDeviceEjection
typeset localBootloader
typeset redColor="\\033[0;31m"
typeset greenColor="\\033[0;32m"
typeset yellowColor="\\033[0;33m"
typeset startUnderline=$(tput smul)
typeset endUnderline=$(tput rmul)
typeset startBold=$(tput bold)
typeset endBold="\e[22m"
boldify() {
echo -e "$startBold$1$endBold"
}
underline() {
echo -e "$startUnderline$1$endUnderline"
}
# $1: The text to colorify.
redify() {
echo -e "$redColor$1\\033[0m"
}
# $1: The text to colorify.
greenify() {
echo -e "$greenColor$1\\033[0m"
}
# $1: The text to colorify.
yellowify() {
echo -e "$yellowColor$1\\033[0m"
}
typeset openTicketMessage="This is not expected: please open a ticket at $ticketsurl."
typeset actionFlagsTable="
-f, --format|Format selected USB drive and exit.
-h, --help|Display this help message and exit.
-i, --inspect|Inspect ISOFILE boot capabilities.
-l, --list-usb-drives|List available USB drives and exit.
-p, --probe|Equivalent to -i followed by -l actions.
-v, --version|Display version and exit.
"
typeset modifierFlagsTable="
-a, --autoselect|In combination with -y, autoselect USB drive when only one is connected.
-d, --device DEVICE|Pick DEVICE block file as target USB drive.
-y, --assume-yes|Don't prompt for confirmation before erasing drive.
-J, --no-eject|Don't eject drive after unmounting.
-H, --no-hash-check|Don't search for hash files and check ISOFILE integrity.
-M, --no-mime-check|Don't check ISOFILE mime-type.
-t, --type FSTYPE|Format to FSTYPE.
-L, --label PARTLABEL|Set partition label to PARTLABEL.
"
typeset installModeModifiersTable="
--icopy, --dd|Install ISOFILE in \"Image-Copy\" mode.
--mrsync|Install ISOFILE in \"Mount-Rsync\" mode.
"
typeset helpIntro="\
$scriptName v$version - create a bootable USB drive from an ISO image."
typeset helpSynopsis="
Usage: $(boldify "$scriptName") [$(underline MODIFIER...)] $(underline ISOFILE)
$(boldify "$scriptName") $(underline ACTION) [$(underline MODIFIER...)] $(underline ISOFILE)
$(boldify "$scriptName") $(underline ACTION)"
typeset helpHint="
Invoked with no ACTION flag, $scriptName will default to install action in automatic mode: inspect ISOFILE \
boot capabilities and find the best way to make a bootable USB drive. \
Read $scriptName man page for a detailed description and advanced options."
displayHelp() {
typeset termwidth=$(tput cols)
echo -e "$helpIntro" | fmt -g "$termwidth" -w "$termwidth"
echo -e "$helpSynopsis"
echo -e "$helpHint" | fmt -g "$termwidth" -w "$termwidth"
echo -e "\n$(boldify 'ACTIONS')"
echo -e "$actionFlagsTable" | column -c "$termwidth" --table -d -N flag,desc -W desc -s \|
echo -e "\n$(boldify 'GENERIC MODIFIERS')"
echo -e "$modifierFlagsTable" | column -c "$termwidth" --table -d -N flag,desc -W desc -s \|
echo -e "\n$(boldify 'INSTALL MODE MODIFIERS')"
echo -e "$installModeModifiersTable" | column -c "$termwidth" --table -d -N flag,desc -W desc -s \|
}
indent() {
sed -e ':a;N;$!ba;s/\n/\n /g'
}
indentAll() {
sed -e 's/^/ /'
}
# $1: The message to print.
echoerr() {
local IFS=$'\n'
redify "$scriptName: $*" | indent >&2
}
# $1: The message to print.
echowarn() {
local IFS=$'\n'
yellowify "$scriptName: $*" | indent
}
# $1: The message to print.
echogood() {
local IFS=$'\n'
greenify "$scriptName: $*" | indent
}
# $1: The message to print.
echoinfo() {
local IFS=$'\n'
echo -e "$scriptName: $*" | indent
}
# $1: The message to print.
failAndExit() {
echoerr "$@" "Exiting..."
exit 1
}
compute() {
answer=$(echo "$@" | bc)
if ((answer == 0)); then
return 1
else
return 0
fi
}
# $1: The name of the command to check against $PATH.
hasPackage() {
command -v "$1" &>/dev/null
return $?
}
configureFolders() {
typeset defaultMode=777
if [ ! -e "$tempRoot" ]; then
mkdir -m $defaultMode "$tempRoot"
elif [ -d "$tempRoot" ]; then
chmod -R $defaultMode "$tempRoot"
else
failAndExit "Unexpected state: '$tempRoot' is not a folder." \
"Remove this file and try again."
fi
if [ ! -e "$cacheRoot" ]; then
mkdir -m $defaultMode "$cacheRoot"
elif [ -d "$cacheRoot" ]; then
chmod -R $defaultMode "$cacheRoot"
else
failAndExit "Unexpected state: '$cacheRoot' is not a folder." \
"Remove this file and try again."
fi
if [ ! -e "$mountRoot" ]; then
mkdir "$mountRoot"
elif [ ! -d "$mountRoot" ]; then
failAndExit "Unexpected state: '$mountRoot' is not a folder." \
"Remove this file and try again."
fi
}
isMounted() {
if [ ! -z "$1" ] && grep -q -e "$1" /etc/mtab; then
return 0
else
return 1
fi
}
umountUSB() {
if isMounted "$usbMountPoint"; then
if umount "$usbMountPoint" |& indentAll; then
echogood "USB device partition succesfully unmounted."
else
echowarn "Could not unmount USB mount point."
fi
fi
}
umountISO() {
if isMounted "$isoMountPoint"; then
if umount "$isoMountPoint" |& indentAll; then
echogood "ISO succesfully unmounted ($isoMountPoint)."
else
echowarn "Could not unmount ISO mount point."
fi
fi
}
initPckgManager() {
if hasPackage apt-get; then # Debian
pkgmgr="apt-get install"
return 0
fi
if hasPackage dnf; then # Fedora
pkgmgr="dnf install"
return 0
fi
if hasPackage yum; then # Fedora
pkgmgr="yum install"
return 0
fi
if hasPackage pacman; then # Arch
pkgmgr="pacman -S"
return 0
fi
if hasPackage zypper; then # OpenSuse
pkgmgr="zypper install"
return 0
fi
if hasPackage emerge; then # Gentoo
pkgmgr="emerge"
return 0
fi
if hasPackage xbps-install; then # Void
pkgmgr="xbps-install"
return 0
fi
return 1
}
checkSudo() {
if ((EUID != 0)); then
if [[ -t 1 ]]; then
sudo --preserve-env "$0" "$@"
else
exec 1>output_file
gksu --preserve-env "$0" "$@"
fi
exit
fi
}
failISOCheck() {
echoerr "Provided file '$selectedIsoFile' doesn't seem to be an ISO file (wrong mime-type: '$mimetype')."
echowarn "You can bypass this policy with $(boldify '-M, --no-mime-check')$yellowColor, but it is likely that the operation will fail."
failAndExit "Exiting..."
}
assertISOIsOK() {
typeset mimetype
typeset -i isOctetStream
if [ -z "$selectedIsoFile" ]; then
echoerr "Missing argument 'iso-file'."
exit 2
fi
if [ -d "$selectedIsoFile" ]; then
failAndExit "Provided file '$selectedIsoFile' is a directory."
fi
if [ ! -f "$selectedIsoFile" ]; then
failAndExit "Provided iso file '$selectedIsoFile' does not exist."
fi
if [ "$disableMimeCheck" == 'false' ]; then
mimetype=$(file --mime-type -b -- "$selectedIsoFile")
[ "$mimetype" == "application/octet-stream" ]
isOctetStream=$?
if ((isOctetStream != 0)) && [ ! "$mimetype" == "application/x-iso9660-image" ]; then
failISOCheck
fi
fi
}
checkISOHash() {
typeset lHash
computeHashWithProgress() {
local hashName="$1"
local isoName="$2"
typeset hashStoreFile=$(createTempFile "bootiso-file-hash")
echoinfo "Checking hash for '$isoName'..."
printf "%s%s" \
"You can disable this check with $(boldify "-H, --no-hash-check") flags" \
" " | indentAll
temporaryAssets+=("$hashStoreFile")
(
local hash
local -i status=0
hash=$($hashName "$isoName" | awk "{print \$1; exit }")
status=$?
if ((status == 0)); then
printf "%s" "$hash" >"$hashStoreFile"
else
printf "%s" 1 >"$hashStoreFile"
fi
) &
pid=$!
while [ -e "/proc/$pid" ]; do
updateProgress
done
cleanProgress
lHash=$(cat "$hashStoreFile")
if [ "$lHash" == "1" ]; then
return 1
fi
}
checkHash() {
typeset hashPath=$1 # Path to file containing hashes
typeset isoName=$2 # File to be checked
typeset hashName=$3 # Name of command of hash
local status
# Hash from hash file
typeset gHash=$(awk -v pattern="$isoName$" '$0 ~ pattern { print $1; exit }' "$hashPath")
if [ -z "$gHash" ]; then
echoerr "No matching filename found in hash file '$hashPath'"
return
elif [ -z "$hashName" ]; then
case ${#gHash} in
32)
hashName="md5sum"
;;
40)
hashName="sha1sum"
;;
64)
hashName="sha256sum"
;;
128)
hashName="sha512sum"
;;
*)
failAndExit "Matching line in '$hashPath' has an unexpected hash format."
;;
esac
fi
# Hash from iso
computeHashWithProgress $hashName "$isoName"
status=$?
if ((status != 0)); then
failAndExit "$hashName command failed with status $status"
fi
if [ "$gHash" != "$lHash" ]; then
if [ "$forceHashCheck" == 'true' ]; then
failAndExit "Hash mismatch in '$hashPath' (${hashName%sum})."
else
echowarn "Hash mismatch in '$hashPath' (${hashName%sum})."
typeset answer
read -r -n1 -p "Do you still want to continue? (y/n)> " answer
echo
case $answer in
y | Y)
return
;;
*)
failAndExit
;;
esac
echoinfo "Ignoring mismatching hash."
fi
else
echogood "Matching ${hashName%sum} hash found in '$hashPath'"
numValidHashes=$((numValidHashes + 1))
fi
}
typeset numValidHashes=0
typeset isoDirectory=$(dirname "$selectedIsoFile")
typeset isoFileName=$(basename "$selectedIsoFile")
typeset -ar hashes=("md5sum" "sha1sum" "sha256sum" "sha512sum")
if [ -n "$hashFile" ]; then
if [ -f "$hashFile" ]; then
checkHash "$hashFile" "$isoFileName"
else
failAndExit "Specified hash file '$hashFile' does not exist."
fi
else
shopt -s nullglob nocaseglob
for hash in "${hashes[@]}"; do
for file in "$isoDirectory/$hash"*; do
checkHash "$file" "$isoFileName" "$hash"
done
if [ -f "$selectedIsoFile.${hash%sum}" ]; then
checkHash "$selectedIsoFile.${hash%sum}" "$isoFileName" "$hash"
fi
done
shopt -u nullglob nocaseglob
fi
if [ "$forceHashCheck" == 'true' ] && [ $numValidHashes == 0 ]; then
failAndExit "No matching hashes found. Assert forced by $(boldify '--force-hash-check')"
fi
}
firstMatchInFolder() {
find "$1" -type f -iname "$2" -print -quit
}
matchFirstExpression() {
typeset root=$1
typeset expr
typeset match
shift
for expr in "$@"; do
match=$(firstMatchInFolder "$root" "$expr")
if [ ! -z "$match" ]; then
echo "$match"
break
fi
done
}
findFileFromPatterns() {
typeset root=$1
shift
typeset loc
typeset found
for loc in "$@"; do
if [ -f "${root}/$loc" ]; then
found="${root}/$loc"
break
fi
done
if [ -z "$found" ]; then
for loc in "$@"; do
typeset candidate=$(find "$root" -type f -path "*/$loc" -print -quit)
if [ ! -z "$candidate" ]; then
found="$candidate"
break
fi
done
fi
echo "$found"
}
configureLabel() {
partitionLabel=${partitionLabel:-$(blkid -o value -s LABEL -- "$selectedIsoFile")}
case $partitionType in
vfat)
# Label to uppercase, otherwise some DOS systems won't work properly
partitionLabel=${partitionLabel^^}
# FAT32 labels have maximum 11 chars
partitionLabel=${partitionLabel:0:11}
;;
exfat)
# EXFAT labels have maximum 15 chars
partitionLabel=${partitionLabel:0:15}
;;
ntfs)
# NTFS labels have maximum 32 chars
partitionLabel=${partitionLabel:0:32}
;;
ext2 | ext3 | ext4)
# EXT labels have maximum 16 chars
partitionLabel=${partitionLabel:0:16}
;;
*)
echowarn "Unexpected partition type '$partitionType'." \
"$openTicketMessage"
;;
esac
# Fallback to "BOOTISO"
partitionLabel=${partitionLabel:-"BOOTISO"}
if [ -z "${userVars['label']}" ]; then
echogood "Partition label automatically set to '$partitionLabel'." \
"You can explicitly set the label with $(boldify '-L, --label')$greenColor."
else
echogood "Partition label manually set to '$partitionLabel'."
fi
}
# $1: The name of the package command to check.
checkpkg() {
typeset answer
if ! hasPackage "$1"; then
echowarn "Command '$1' not found! Should be in package '${commandPackages["$1"]}'."
if [ ! -z "$pkgmgr" ]; then
read -r -n1 -p "Attempt installation? (y/n)> " answer
echo
case $answer in
y | Y)
if ! $pkgmgr "${commandPackages["$1"]}"; then
failAndExit "Installation of dependency '$1' failed." \
"Perhaps this dependency has a slightly different name on your distribution." \
"Find it and install manually."
else
if ! hasPackage "$1"; then
failAndExit "Program '$1' is not accessible in the \$PATH environment even though the package ${commandPackages["$1"]} has just been installed."
fi
fi
;;
*)
failAndExit "Missing dependency '$1'."
;;
esac
else
failAndExit "Missing dependency '$1'."
fi
fi
}
# $1: The string by which elements will be joined.
# $2-* : the elements to join
joinBy() {
local IFS=$1
shift
echo "$*"
}
# $1: The element to check.
# $2-* : the list to check against.
containsElement() {
local e match="$1"
shift
for e; do [[ "$e" == "$match" ]] && return 0; done
return 1
}
initDevicesList() {
typeset -a devices
typeset device
mapfile -t devices < <(lsblk -o NAME,TYPE | grep --color=never -oP '^\K\w+(?=\s+disk$)')
devicesList=()
for device in "${devices[@]}"; do
if [ "$(getDeviceType "/dev/$device")" == "usb" ] || [ "$disableUSBCheck" == 'true' ]; then
devicesList+=("$device")
fi
done
}
listDevicesTable() {
typeset lsblkCmd='lsblk -o NAME,MODEL,VENDOR,SIZE,TRAN,HOTPLUG,SERIAL'
initDevicesList
if [ "$disableUSBCheck" == 'true' ]; then
echoinfo "Listing drives available in your system:"
else
echoinfo "Listing USB devices available in your system:"
fi
if [ "${#devicesList[@]}" -gt 0 ]; then
$lsblkCmd | sed -n 1p | sed 's/^/ /'
$lsblkCmd | grep --color=never -P "^($(joinBy '|' "${devicesList[@]}"))" | sed 's/^/ /'
return 0
else
echowarn "Couldn't find any USB drives on your system." \
"If one is physically plugged in, it's likely that it has been ejected and should be reconnected." \
"You can check the availability of USB drives with '$scriptName -l'."
return 1
fi
}
parseArguments() {
enableUserFlag() {
userFlags["$1"]=true
}
setUserVar() {
userVars["$1"]=$2
}
typeset key
typeset isEndOfOptions=false
while [[ $# -gt 0 ]]; do
key="$1"
if [ "$isEndOfOptions" == 'false' ]; then
case $key in
# ACTIONS
-h | --help | help)
enableUserFlag 'help'
shift
;;
-v | --version)
enableUserFlag 'version'
shift
;;
-l | --list-usb-drives)
enableUserFlag 'list-usb-drives'
shift
;;
-p | --probe)
enableUserFlag 'probe'
shift
;;
-f | --format)
enableUserFlag 'format'
shift
;;
-i | --inspect)
enableUserFlag 'inspect'
shift
;;
--dd | --icopy)
enableUserFlag 'install-dd'
shift
;;
--mrsync)
enableUserFlag 'install-mount-rsync'
shift
;;
# OPTIONS
-b | --bootloader)
echowarn "$(boldify '-b, --bootloader')$yellowColor has been removed in v3.0.0. Bootloader installation is now automatic."
shift
;;
--local-bootloader)
enableUserFlag 'local-bootloader'
shift
;;
--remote-bootloader)
if (($# < 2)); then
failAndExit "Missing value for '$1' flag. Please provide a version following MAJOR.MINOR pattern. ex: '4.10'."
fi
setUserVar 'remote-bootloader' "$2"
shift 2
;;
-y | --assume-yes)
enableUserFlag 'assume-yes'
shift
;;
-d | --device)
if (($# < 2)); then
failAndExit "Missing value for '$1' flag. Please provide a device."
fi
setUserVar 'device' "$2"
shift 2
;;
-t | --type)
if (($# < 2)); then
failAndExit "Missing value for '$1' flag. Please provide a filesystem type."
fi
setUserVar 'type' "${2,,}" #lowercased
shift 2
;;
-L | --label)
if (($# < 2)); then
failAndExit "Missing value for '$1' flag. Please provide a label."
fi
setUserVar 'label' "$2"
shift 2
;;
--hash-file)
if (($# < 2)); then
failAndExit "Missing value for '$1' flag. Please provide a hash file."
fi
setUserVar 'hash-file' "$2"
shift 2
;;
-J | --no-eject)
enableUserFlag 'no-eject'
shift
;;
-H | --no-hash-check)
enableUserFlag 'no-hash-check'
shift
;;
-a | --autoselect)
enableUserFlag 'autoselect'
shift
;;
-M | --no-mime-check)
enableUserFlag 'no-mime-check'
shift
;;
--no-usb-check)
enableUserFlag 'no-usb-check'
shift
;;
--no-size-check)
enableUserFlag 'no-size-check'
shift
;;
--force-hash-check)
enableUserFlag 'force-hash-check'
shift
;;
--no-wimsplit)
enableUserFlag 'no-wimsplit'
shift
;;
--)
isEndOfOptions=true
shift
;;
-*)
# Probably an option, possibly a file.
if [ ! -f "$key" ]; then
# Assume it's stacked options
if [[ "$key" =~ ^-["$shortOptions"]{2,}$ ]]; then
shift
typeset options=${key#*-}
typeset -a extractedOptions
mapfile -t extractedOptions < <(echo "$options" | grep -o . | xargs -d '\n' -n1 printf '-%s\n')
set -- "${extractedOptions[@]}" "$@"
elif [[ "$key" =~ ^--[a-zA-Z0-9]{2,}$ ]]; then
failAndExit "Unknown option: '$key'"
else
printf "\\e[0;31m%s\\e[m" "$scriptName: Unknown option: "
printf '%s' "$key" | GREP_COLORS='mt=00;32:sl=00;31' grep --color=always -P "[$shortOptions]"
if [[ "$key" =~ ^-[a-zA-Z0-9]+$ ]]; then
typeset wrongOptions=$(printf '%s' "${key#*-}" | grep -Po "[^$shortOptions]" | tr -d '\n')
if [ ${#key} -eq 2 ]; then
yellowify "flag: \\033[0;31m'$wrongOptions'\\033[0m."
else
yellowify "stacked flags: \\033[0;31m'$wrongOptions'\\033[0m."
fi
fi
echoerr "Exiting..."
exit 2
fi
else
# Happened to be a file.
setUserVar 'iso-file' "$1"
shift
fi
;;
*)
setUserVar 'iso-file' "$1"
shift
;;
esac
else
setUserVar 'iso-file' "$1"
break
fi
done
}
checkPackages() {
typeset pkg
for pkg in "${commandDependencies[@]}"; do
checkpkg "$pkg"
done
# test grep supports -P option
if ! echo 1 | grep -P '1' &>/dev/null; then
failAndExit "You're using an old version of grep which does not support perl regular expression (-P option)."
fi
}
# $1 : the folder name prefix
# print the name of the new folder if operation succeeded, fails otherwise
createMountFolder() {
typeset tmpFileTemplate
if ((EUID == 0)); then
tmpFileTemplate="$mountRoot/$1-XXX"
else
tmpFileTemplate="$tempRoot/$1-XXX"
fi
mktemp -d "$tmpFileTemplate"
typeset status=$?
if [ ! $status -eq 0 ]; then
failAndExit "Failed to create temporary mount point with pattern '$tmpFileTemplate'."
fi
}
createTempFile() {
typeset tmpFileTemplate="$tempRoot/$1-XXX"
mktemp "$tmpFileTemplate"
typeset status=$?
if [ ! $status -eq 0 ]; then
failAndExit "Failed to create temporary file."
fi
}
mountISOFile() {
isoMountPoint=$(createMountFolder iso) || exit "$?"
temporaryAssets+=("$isoMountPoint")
echogood "Created ISO mount point at '$isoMountPoint'."
if ! mount -r -o loop -- "$selectedIsoFile" "$isoMountPoint" >/dev/null; then
failAndExit "Could not mount ISO file."
fi
}
# $1 : a device block
# Returns "usb" if device is USB, "ata" for SATA
getDeviceType() {
typeset deviceName=/sys/block/${1#/dev/}
typeset deviceType=$(udevadm info --query=property --path="$deviceName" | grep -Po 'ID_BUS=\K\w+')
echo "$deviceType"
}
deviceIsDisk() {
lsblk --nodeps -o NAME,TYPE "$1" | grep -q disk
return $?
}
selectDevice() {
typeset _selectedDevice
chooseDevice() {
echoinfo "Select the device corresponding to the USB device you want to make bootable: $(joinBy ',' "${devicesList[@]}")" \
"Type CTRL+D to quit."
read -r -p "Select device id> " _selectedDevice
echo
if containsElement "$_selectedDevice" "${devicesList[@]}"; then
selectedDevice="/dev/$_selectedDevice"
else
if containsElement "$_selectedDevice" "" "exit"; then
echoinfo "Exiting on user request."
exit 0
else
failAndExit "The drive $_selectedDevice does not exist."
fi
fi
}
handleDeviceSelection() {
if [ ${#devicesList[@]} -eq 1 ] && [ "$disableUSBCheck" == 'false' ]; then
# autoselect
if [ "$disableConfirmation" == 'false' ] || { [ "$disableConfirmation" == 'true' ] && [ "$autoselect" == 'true' ]; }; then
typeset selected="${devicesList[0]}"
echogood "Autoselecting '$selected' (only USB device candidate)"
selectedDevice="/dev/$selected"
else
chooseDevice
fi
else
chooseDevice
fi
}
if [ -z "$selectedDevice" ]; then
# List all hard disk drives
if listDevicesTable; then
handleDeviceSelection
else
echoerr "Exiting..."
exit 1
fi
fi
selectedPartition="${selectedDevice}1"
}
assertDeviceIsOK() {
failDevice() {
echoerr "$1"
listDevicesTable
echoerr "Exiting..."
exit 1
}
typeset -r device=$1
if [ ! -e "$device" ]; then
failDevice "The selected device '$device' does not exist."
fi
if [ ! -b "$device" ]; then
failDevice "The selected device '$device' is not a valid block file."
fi
if [ ! -d "/sys/block/$(basename "$device")" ] || ! deviceIsDisk "$device"; then
failAndExit "The selected device '$device' is either unmounted or not a disk (might be a partition or loop)." \
"Select a disk instead or reconnect the USB device." \
"You can check the availability of USB drives with '$scriptName -l'."
fi
}
assertDeviceIsUSB() {
typeset deviceType
if [ "$disableUSBCheck" == 'true' ]; then
echowarn "USB check has been disabled. Skipping."
return 0
fi
deviceType=$(getDeviceType "$selectedDevice")
if [ "$deviceType" != "usb" ]; then
echoerr "The device you selected is not connected via USB (found BUS: '$deviceType') and the operation was therefore canceled."
echowarn "Use $(boldify '--no-usb-check')$yellowColor to bypass this policy at your own risk."
echoerr "Exiting..."