-
Notifications
You must be signed in to change notification settings - Fork 314
/
winusb
executable file
·1035 lines (887 loc) · 27.1 KB
/
winusb
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
# shellcheck disable=SC2026
# SC2026 disabled because of false positives(ShellCheck issue #923)
# A Linux program to create bootable Windows USB stick from a real Windows DVD or an image
# Copyright © 2013 Colin GILLE / congelli501
# Copyright © 2017 slacka et. al.
# This file is part of WinUSB.
#
# WinUSB is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# WinUSB is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with WinUSB If not, see <http://www.gnu.org/licenses/>.
# Notes:
#
# * Use --strip instead of --no-symlinks for compatibility of Ubuntu 14.04(EoL: April 2019)
## Makes debuggers' life easier - Unofficial Bash Strict Mode
## BASHDOC: Shell Builtin Commands - Modifying Shell Behavior - The Set Builtin
set -o errexit
set -o errtrace
set -o nounset
set -o pipefail
for critical_command in realpath basename dirname; do
if ! command -v "${critical_command}" &> /dev/null; then
echo "Fatal: This program requires GNU Coreutils in the executable search path"
exit 1
fi
done
## Non-overridable Primitive Variables
## BASHDOC: Shell Variables » Bash Variables
## BASHDOC: Basic Shell Features » Shell Parameters » Special Parameters
if [ -v "BASH_SOURCE[0]" ]; then
RUNTIME_EXECUTABLE_PATH="$(realpath --strip "${BASH_SOURCE[0]}")"
RUNTIME_EXECUTABLE_FILENAME="$(basename "${RUNTIME_EXECUTABLE_PATH}")"
RUNTIME_EXECUTABLE_NAME="${RUNTIME_EXECUTABLE_FILENAME%.*}"
RUNTIME_EXECUTABLE_DIRECTORY="$(dirname "${RUNTIME_EXECUTABLE_PATH}")"
RUNTIME_COMMANDLINE_BASECOMMAND="${0}"
# Keep these partially unused variables declared
# shellcheck disable=SC2034
declare -r\
RUNTIME_EXECUTABLE_PATH\
RUNTIME_EXECUTABLE_FILENAME\
RUNTIME_EXECUTABLE_NAME\
RUNTIME_EXECUTABLE_DIRECTORY\
RUNTIME_COMMANDLINE_BASECOMMAND
fi
declare -ar RUNTIME_COMMANDLINE_PARAMETERS=("${@}")
declare -r APPLICATION_NAME="WinUSB"
declare -i\
verbose='0'\
only_for_gui='0'\
no_color='0'
# Commands that needs to be determined in runtime
# due to different names in distributions
declare\
command_mkdosfs\
command_grubinstall
declare -ir DD_BLOCK_SIZE="((4 * 1024 * 1024))" # 4MiB
# FIXME: No documentation for this non-trivial parameter
declare -i pulse_current_pid=0
init(){
local install_mode
# source_media may be a optical disk drive or a disk image
# target_media may be an entire usb storage device or just a partition
local\
source_media\
target_media
local\
target_device\
target_partition
local\
source_fs_mountpoint\
target_fs_mountpoint
source_fs_mountpoint="/media/winusb_source_$(date +%s)_$$"
target_fs_mountpoint="/media/winusb_target_$(date +%s)_$$"
if ! check_runtime_dependencies; then
exit 1
fi
if ! process_commandline_parameters\
install_mode\
source_media\
target_media; then
print_help
exit 1
fi
check_permission
check_runtime_parameters\
install_mode\
source_media\
target_media
pulse on
determine_target_parameters\
"${install_mode}"\
target_device\
target_partition
check_source_and_target_not_busy\
"${install_mode}"\
"${source_media}"\
"${target_device}"\
"${target_partition}"
if [ "${install_mode}" = 'device' ]; then
destroy_and_rebuild_entire_disk\
"${target_device}"\
"${target_partition}"
fi
if [ "${install_mode}" = 'partition' ]; then
check_target_filesystem "${target_partition}"
fi
setup_traps
mount_source_and_target_filesystem\
"${source_media}"\
"${source_fs_mountpoint}"\
"${target_partition}"\
"${target_fs_mountpoint}"\
|| (
echo_with_color red "Error: Failed to mount filesystems"\
exit 1
)
check_target_filesystem_free_space\
"${target_fs_mountpoint}"\
"${source_fs_mountpoint}"\
|| exit 1
copy_filesystem_files\
"${source_fs_mountpoint}"\
"${target_fs_mountpoint}"
workaround_support_windows_7_uefi_boot\
"${source_fs_mountpoint}"\
"${target_fs_mountpoint}"
install_bootloader_grub\
"${target_fs_mountpoint}"\
"${target_device}"
cleanup_mountpoints\
"${source_fs_mountpoint}"\
"${target_fs_mountpoint}"\
'normal_cleanup'
echo_with_color green "Done :-) You may detach the usb storage now."
pulse off
exit 0
}; declare -fr init
check_target_filesystem_free_space(){
util_check_function_parameters_quantity 2 $#
local -r target_fs_mountpoint="${1}"; shift
local -r source_fs_mountpoint="${1}"
free_space=$(\
df\
--block-size=1\
"${target_fs_mountpoint}"\
| grep "${target_fs_mountpoint}"\
| awk '{print $4}'\
)
free_space_human_readable=$(\
df\
--human-readable\
"${target_fs_mountpoint}"\
| grep "${target_fs_mountpoint}"\
| awk '{print $4}'\
)
needed_space=$(\
du\
--summarize\
--bytes\
"${source_fs_mountpoint}"\
| awk '{print $1}'\
)
needed_space_human_readable=$(\
du\
--summarize\
--human-readable\
"${source_fs_mountpoint}"\
| awk '{print $1}'\
)
additional_space_required_for_grub_installation="$((1000 * 1000 * 10))" # 10MiB
((needed_space = needed_space + additional_space_required_for_grub_installation))
if [ "${needed_space}" -gt "${free_space}" ]; then
echo "Error: Not enough free space on target partition!" >&2
echo "Error: We required ${needed_space_human_readable}(${needed_space} bytes) but '${target_partition}' only has ${free_space_human_readable}(${free_space} bytes)." >&2
return 1
fi
}; declare -fr check_target_filesystem_free_space
check_target_filesystem(){
util_check_function_parameters_quantity 1 $#
local target_partition="${1}"
local target_filesystem
target_filesystem="$(\
lsblk\
--output FSTYPE\
--noheadings\
"${target_partition}"\
)"
if [ "${target_filesystem}" != "vfat" ]; then
echo_with_color "${FUNCNAME[0]}: Error: Target filesystem not supported, currently supported filesystem: FAT"
return 1
fi
return 0
}; declare -fr check_target_filesystem
check_permission(){
if [ ! "$(id --user)" = 0 ]; then
printf --\
"%s\n%s\n"\
"Warning: You are not running WinUSB as root!"\
"Warning: This might be the reason of the following failure." >&2
fi
return 0
}; declare -fr check_permission
check_source_and_target_not_busy(){
util_check_function_parameters_quantity 4 $#
local install_mode="$1"; shift
local source_media="$1"; shift
local target_device="$1"; shift
local target_partition="$1"
if [ "$(mount | grep -c "${source_media}")" != 0 ]; then
echo_with_color red "Error: Source media is currently mounted, unmount the partition then try again"
exit 1
fi
if [ "${install_mode}" = "partition" ]; then
if [ "$(mount | grep -c "${target_partition}")" != 0 ]; then
echo_with_color red "Error: Target partition is currently mounted, unmount the partition then try again"
exit 1
fi
else # When install_mode = device, all target partitions needs to by unmounted
if [ "$(mount | grep -c "${target_device}")" != 0 ]; then
echo_with_color red "Error: Target device is currently busy, unmount all mounted partitions in target device then try again"
exit 1
fi
fi
}; declare -fr check_source_and_target_not_busy
determine_target_parameters(){
util_check_function_parameters_quantity 3 $#
local install_mode="${1}"; shift
local -n target_device_ref="${1}"; shift
local -n target_partition_ref="${1}"; shift
if [ "${install_mode}" = 'partition' ]; then
target_partition_ref="${target_media}"
# BASHDOC: Basic Shell Features » Shell Expansions » Shell Parameter Expansion(`${PARAMETER/PATTERN/STRING}')
target_device_ref="${target_media/%[0-9]/}"
else # install_mode = device
target_device_ref="${target_media}"
target_partition_ref="${target_device}1"
fi
if [ "${verbose}" = '1' ]; then
echo "${FUNCNAME[0]}: Info: Target device is '${target_device_ref}'."
echo "${FUNCNAME[0]}: Info: Target partition is '${target_partition_ref}'."
fi
return 0
}; declare -fr determine_target_parameters
install_bootloader_grub(){
util_check_function_parameters_quantity 2 "${#}"
local -r target_fs_mountpoint="${1}"; shift 1
local -r target_device="${1}"
echo_with_color blue "Installing GRUB bootloader for legacy boot support..."
"${command_grubinstall}"\
--target=i386-pc\
--boot-directory="${target_fs_mountpoint}"\
--force "${target_device}"
echo_with_color blue "Installing grub.cfg..."
local -r grub_cfg="${target_fs_mountpoint}/grub/grub.cfg"
local -r target_fs_uuid=$(\
lsblk\
--output UUID\
--noheadings\
"${target_device}"\
)
mkdir --parents "$(dirname "${grub_cfg}")"
{
cat <<- END_OF_FILE
echo '------------------------------------'
echo '| Windows USB - Loading... |'
echo '------------------------------------'
insmod fat
search --no-floppy --fs-uuid ${target_fs_uuid} --set root
ntldr /bootmgr
boot
END_OF_FILE
} > "${grub_cfg}"
}; declare -fr install_bootloader_grub
# As Windows 7's installation media doesn't place the required EFI
# bootloaders in the right location, we extract them from the
# system image manually
# TODO: Functionize Windows 7 checking
workaround_support_windows_7_uefi_boot(){
util_check_function_parameters_quantity 2 "${#}"
local source_fs_mountpoint="${1}"; shift
local target_fs_mountpoint="${1}"
if \
grep\
--extended-regexp\
--quiet\
"^MinServer=7[0-9]{3}\.[0-9]"\
"${source_fs_mountpoint}/sources/cversion.ini"\
&& [ -f "${source_fs_mountpoint}/bootmgr.efi" ]; then
echo_with_color yellow "Source media seems to be Windows 7-based with EFI support, applying workaround to make it support UEFI booting"
if command -v "7z" >/dev/null 2>&1; then
mkdir\
--parents\
"${target_fs_mountpoint}/EFI/Boot"
7z\
# extract \
e\
# Write data to StdOut \
-so\
"${source_fs_mountpoint}/sources/install.wim"\
"1/Windows/Boot/EFI/bootmgfw.efi"\
> "${target_fs_mountpoint}/EFI/Boot/bootx64.efi"
else
echo_with_color yellow "Warning: '7z' utility not found, workaround is not applied." >&2
fi
fi
}; declare -fr workaround_support_windows_7_uefi_boot
mount_source_and_target_filesystem(){
util_check_function_parameters_quantity 4 "${#}"
local source_media="$1"; shift
local source_fs_mountpoint="$1"; shift
local target_partition="$1"; shift
local target_fs_mountpoint="$1"
echo_with_color blue "Mounting source and target filesystems..."
mkdir\
--parents\
"${source_fs_mountpoint}"\
|| (
echo_with_color red "${FUNCNAME[0]}: Error: Unable to create \"${source_fs_mountpoint}\" mountpoint directory"
return 1
)
if [ -f "${source_media}" ]; then # ${source_media} is an ISO image
mount\
--options loop,ro\
--types udf,iso9660\
"${source_media}"\
"${source_fs_mountpoint}"\
|| (
echo_with_color red "${FUNCNAME[0]}: Error: Unable to mount source media"
return 1
)
else # ${source_media} is a real optical disk drive (block device)
mount\
--options ro\
"${source_media}"\
"${source_fs_mountpoint}"\
|| (
echo_with_color red "${FUNCNAME[0]}: Error: Unable to mount source media"
return 1
)
fi
mkdir\
--parents\
"${target_fs_mountpoint}"\
|| (
echo_with_color red "${FUNCNAME[0]}: Error: Unable to create \"${target_fs_mountpoint}\" mountpoint directory"
return 1
)
mount\
"${target_partition}"\
"${target_fs_mountpoint}"\
|| (
echo_with_color red "${FUNCNAME[0]}: Error: Unable to mount target partition"
return 1
)
}; declare -fr mount_source_and_target_filesystem
setup_traps(){
util_check_function_parameters_quantity 0 "${#}"
trap 'cleanup_mountpoints "${source_fs_mountpoint}" "${target_fs_mountpoint}" "error"' ERR
trap 'cleanup_mountpoints "${source_fs_mountpoint}" "${target_fs_mountpoint}" "interrupt"' INT
trap 'cleanup_mountpoints "${source_fs_mountpoint}" "${target_fs_mountpoint}" "kill"' TERM
trap 'cleanup_mountpoints "${source_fs_mountpoint}" "${target_fs_mountpoint}" "exit"' EXIT
trap 'cleanup_mountpoints "${source_fs_mountpoint}" "${target_fs_mountpoint}" "other signal"' HUP QUIT PIPE
}; declare -fr setup_traps
# Utility function to check if function parameters quantity is legal
# NOTE: non-static function parameter quantity(e.g. either 2 or 3) is not supported
util_check_function_parameters_quantity(){
if [ "${#}" -ne 2 ]; then
printf --\
"%s: FATAL: Function requires %u parameters, but %u is given\n"\
"${FUNCNAME[0]}"\
2\
"${#}"
exit 1
fi
# The expected given quantity
local -i expected_parameter_quantity="${1}"; shift
# The actual given parameter quantity, simply pass "${#}" will do
local -i given_parameter_quantity="${1}"
if [ "${given_parameter_quantity}" -ne "${expected_parameter_quantity}" ]; then
printf --\
"%s: FATAL: Function requires %u parameters, but %u is given\n"\
"${FUNCNAME[1]}"\
"${expected_parameter_quantity}"\
"${given_parameter_quantity}"\
1>&2
exit 1
fi
return 0
}; declare -fr util_check_function_parameters_quantity
destroy_and_rebuild_entire_disk(){
util_check_function_parameters_quantity 2 $#
local -r target_device="${1}"; shift
local -r target_partition="${1}"
echo_with_color blue "DESTROYING previous data on \"${target_device}\" and reintializing ..."
# Create new PC, a.k.a. MBR, a.k.a. msdos style partition table(and overwrite the old one, whatever it was)
parted --script\
"${target_device}"\
mklabel\
msdos
# Create partition
# We start at 4MiB for grub (it needs a post-mbr gap for its code) and alignment of flash memery block erase segment in general, for details see http://www.gnu.org/software/grub/manual/grub.html#BIOS-installation and http://lwn.net/Articles/428584/
parted --script\
"${target_device}"\
mkpart\
primary\
fat32\
4MiB\
-- -1s # last sector of the disk
# Reload the new partition table
# FIXME: Is `blockdev` and `partprobe` both required?
blockdev\
--rereadpt\
"${target_device}"\
|| true
partprobe\
"${target_device}"
echo "Wait 3 seconds for block device nodes to populate..."
sleep 3
# Create filesystem on partition
"$command_mkdosfs"\
-F 32\
-n 'Windows USB' \
"${target_partition}"
}; declare -fr destroy_and_rebuild_entire_disk
check_runtime_dependencies(){
util_check_function_parameters_quantity 0 $#
local result="unknown"
for required_command in\
mount\
grep\
dd\
id\
mkdir\
df\
du\
awk\
parted\
blockdev\
partprobe\
stat\
rm\
readlink\
find\
lsblk
do
if ! command -v "${required_command}" >/dev/null; then
echo_with_color red "${FUNCNAME[0]}: Error: ${APPLICATION_NAME} requires ${required_command} command in the executable search path, but it is not found."
result=failed
fi
done
if command -v 'mkdosfs' &> /dev/null; then
command_mkdosfs='mkdosfs'
elif command -v 'make.msdos' &> /dev/null; then
command_mkdosfs='mkfs.msdos'
else
echo_with_color red\
"${FUNCNAME[0]}: Error: mkdosfs or mkfs.msdos command not found!" >&2
echo_with_color red\
"${FUNCNAME[0]}: Error: Please make sure that dosfstools is properly installed!" >&2
result="failed"
fi
if command -v 'grub-install' &> /dev/null; then
command_grubinstall='grub-install'
elif command -v 'grub2-install' &> /dev/null; then
command_grubinstall='grub2-install'
else
echo_with_color red "${FUNCNAME[0]}: Error: grub-install or grub2-install command not found!" >&2
echo_with_color red "${FUNCNAME[0]}: Error: Please make sure that GNU GRUB is properly installed!" >&2
result="failed"
fi
if [ "${result}" == "failed" ]; then
return 1
else
return 0
fi
}; declare -fr check_runtime_dependencies
check_runtime_parameters(){
util_check_function_parameters_quantity 3 $#
local -n install_mode_ref="${1}"; shift
local -n source_media_ref="${1}"; shift
local -n target_media_ref="${1}"
if ! util_is_parameter_set_and_not_empty install_mode_ref\
|| ! util_is_parameter_set_and_not_empty source_media_ref\
|| ! util_is_parameter_set_and_not_empty target_media_ref; then
echo_with_color red "${FUNCNAME[0]}: Error: No install method specified!" >&2
echo "" >&2
print_help
exit 1
fi
if [ ! -f "${source_media_ref}" ] \
&& [ ! -b "${source_media_ref}" ]; then
echo_with_color red "${FUNCNAME[0]}: Error: source media \"${source_media_ref}\" not found or not a regular file or a block device file!" >&2
exit 1
fi
if ! [ -b "${target_media_ref}" ]; then
echo_with_color red "${FUNCNAME[0]}: Error: Target media \"${target_media_ref}\" is not a block device file!" >&2
exit 1
fi
return 0
}; declare -fr check_runtime_parameters
pulse(){
util_check_function_parameters_quantity 1 $#
if [ "$only_for_gui" -eq 1 ]; then
if [ ! "$pulse_current_pid" -eq 0 ]; then
kill "$pulse_current_pid"
#wait "$pulse_current_pid"
pulse_current_pid=0
fi
if [ "$1" = 'on' ]; then
cd /; while true; do sleep 0.05; echo 'pulse'; done &
pulse_current_pid="$!"
elif [ "$1" != 'off' ]; then
echo "${FUNCNAME[0]}: Error: Illegal function parameter" >&2
exit 1
fi
fi
}; declare -fr pulse
# Configure the terminal to print future messages with certain color
# $1:
# <color>: color of the next message
# none: reset color to default
switch_terminal_text_color(){
util_check_function_parameters_quantity 1 $#
case "$1" in
none)
tput sgr0
;;
black)
echo -en "\033[0;30m"
;;
red)
echo -en "\033[0;31m"
;;
green)
echo -en "\033[0;32m"
;;
yellow)
echo -en "\033[0;33m"
;;
blue)
echo -en "\033[0;34m"
;;
white)
echo -en "\033[0;37m"
;;
esac
}; declare -fr switch_terminal_text_color
# Print message with color
echo_with_color(){
util_check_function_parameters_quantity 2 "${#}"
local -r message_color="${1}"; shift
local -r message_body="${1}"
if [ "${no_color}" -eq 1 ]; then
echo -e "${message_body}"
else
switch_terminal_text_color "${message_color}"
echo -e "${message_body}"
switch_terminal_text_color none
fi
}
# Unmount mounted filesystems and clean-up mountpoints before exiting program
# $1: Windows ISO mountpoint
# $2: Target mountpoint
# $3: Exit reason
cleanup_mountpoints(){
util_check_function_parameters_quantity 3 "${#}"
set +o errexit # We need to clean up everything we can
trap - HUP QUIT PIPE INT TERM EXIT
pulse off
printf "\n" # Proactively separate from previous command output
if [ "$3" == 'kill' ]; then
echo_with_color yellow "Terminated by external signal!" >&2
elif [ "$3" == 'error' ]; then
echo_with_color red "Internal error occurred!" >&2
elif [ "$3" == 'interrupt' ]; then
echo_with_color yellow "Interrupted by user"
else
echo_with_color green "Exiting..."
fi
echo "Synchronizing cached writes to persistent storage..."
pulse on
sync
pulse off
echo "Cleaning..."
cd /
sync
wait 2> /dev/null
sleep 1
echo_with_color green "Unmounting and removing '$1'..."
# shellcheck disable=2015
umount "$1" && rm -rf "$1" || true
echo_with_color green "Unmounting and removing '$2'..."
# shellcheck disable=2015
umount "$2" && rm -rf "$2" || true
if [ "$3" = 'normal_cleanup' ]; then
return 0
else
exit 2
fi
}
hideNoErr(){
set +o errexit
TEXT="$( "$@" 2>&1 )"
RETURN="$?"
set -o errexit
if [ "$RETURN" -ne 0 ]; then
echo_with_color red "Error while running command '$*' (exit code : $RETURN)!" >&2
echo_with_color red "Read command output (Y/n)?" >&2
rep='y'
read -r rep || true # If we can't read, don't quit
if [ "${rep}" != "n" ] && [ "${rep}" != "N" ]; then
echo "$TEXT"
fi
echo_with_color red "Press ENTER to exit (tmpDir will be removed)" >&2
read -r
fi
return "$RETURN"
}
# Copy source_file to dest_file, overwrite file if dest_file exists
# Also report copy_filesystem_files progress during operation
copy_file(){
util_check_function_parameters_quantity 4 "${#}"
local -r source_file="${1}"; shift
local -r dest_file="${1}"; shift
local -ir caller_copied_size="${1}"; shift
local -ir caller_total_size="${1}"
local -i source_file_size
source_file_size=$(\
stat\
--format=%s\
"${source_file}"\
)
# block count of the source file
local -i block_number
((block_number = source_file_size / DD_BLOCK_SIZE + 1))
unset source_file_size
if [ -f "${dest_file}" ]; then
rm "${dest_file}"
fi
# Copy file block by block
local -i i=0 copied_size_total percentage; while [ "${i}" -lt "${block_number}" ]; do
dd\
if="${source_file}"\
bs="${DD_BLOCK_SIZE}"\
skip="${i}"\
seek="${i}"\
of="${dest_file}"\
count=1\
2> /dev/null
((i = i + 1))
((copied_size_total = caller_copied_size + DD_BLOCK_SIZE * i ))
((percentage = (copied_size_total * 100) / caller_total_size))
echo -en "${percentage}%\r"
done; unset i copied_size_total percentage
return 0
}; declare -fr copy_file
# Copying all files from one filesystem to another, with progress reporting
copy_filesystem_files(){
util_check_function_parameters_quantity 2 "${#}"
local source_fs_mountpoint="${1}"; shift
local target_fs_mountpoint="${1}"
local -i total_size
total_size=$(\
du\
--summarize\
--bytes\
"${source_fs_mountpoint}"\
| awk '{print $1}'\
)
# FIXME: Why do we `pulse off` and on here?
pulse off
echo_with_color blue "Copying files from source media..."
pushd "${source_fs_mountpoint}"
file_list=$(\
find\
.\
-not -path "."\
-print0\
)
local -i copied_size=0 percentage; while IFS='' read -r -d '' source_file; do
dest_file="${target_fs_mountpoint}/${source_file}"
source_file_size=$(\
stat\
--format=%s\
"${source_file}"\
)
if [ -d "${source_file}" ]; then
mkdir --parents "${dest_file}"
elif [ -f "${source_file}" ]; then
if [ "${source_file_size}" -lt "${DD_BLOCK_SIZE}" ]; then
cp "${source_file}" "${dest_file}"
else
copy_file\
"${source_file}"\
"${dest_file}"\
"${copied_size}"\
"${total_size}"
fi
else
echo_with_color red "${FUNCNAME[0]}: Error: Unknown type of '${source_file}'!" >&2
exit 1
fi
# Report progress
((copied_size = copied_size + source_file_size))
((percentage = (copied_size * 100) / total_size))
echo -en "${percentage}%\r"
done < <(echo "${file_list}"); unset source_file dest_file source_file_size copied_size percentage percentage
popd
pulse on
return 0
}
print_help(){
util_check_function_parameters_quantity 0 "${#}"
echo -e "${APPLICATION_NAME}'s Help"
echo -e "=========================="
echo -e "Convert a bootable Windows media to a bootable USB storage device"
echo -e
echo -e "Copy Windows files to an existing FAT partition of an USB storage and make it bootable"
echo -e "NOTE: All files that has the same name will be OVERWRITTEN!"
echo -e "\t""${RUNTIME_EXECUTABLE_NAME} --install <source media path> <partition>"
echo -e "\t""Example: ${RUNTIME_EXECUTABLE_NAME} --install win7_amd64.iso /dev/sdX1"
echo -e "\t""Example: ${RUNTIME_EXECUTABLE_NAME} --install /dev/sr0 /dev/sdX1"
echo -e
echo -e "Completely DESTROY all previous data on an USB storage, copy Windows files and make it bootable"
echo -e "\t""${RUNTIME_EXECUTABLE_NAME} --format <source media path> <device>"
echo -e "\t""Example: ${RUNTIME_EXECUTABLE_NAME} --format win7_amd64.iso /dev/sdX"
echo -e "\t""Example: ${RUNTIME_EXECUTABLE_NAME} --format /dev/sr0 /dev/sdX"
echo -e
echo -e "Options"
echo -e "\t--verbose, -v ""Verbose mode"
echo -e "\t--help, -h ""Show this help message and exit"
echo -e "\t--no-color ""Disable color"
echo -e "\t--debug, -d ""Enable script debugging"
}; declare -fr print_help
process_commandline_parameters(){
util_check_function_parameters_quantity 3 "${#}"
local -n install_mode_ref="${1}"; shift
local -n source_media_ref="${1}"; shift
local -n target_media_ref="${1}"
if [ "${#RUNTIME_COMMANDLINE_PARAMETERS[@]}" -eq 0 ]; then
print_help
exit 0
fi
local -a parameters=("${RUNTIME_COMMANDLINE_PARAMETERS[@]}")
local enable_debug=N
while [ "${#parameters[@]}" -ne 0 ]; do
case "${parameters[0]}" in
"--help"\
|"-h")
print_help;
exit 0
;;
"--debug"\
|"-d")
enable_debug="Y"
;;
'--install')
install_mode_ref='partition'
shift_array parameters
if [ "${#parameters[@]}" -lt 2 ]; then
echo_with_color\
"red"\
"${FUNCNAME[0]}: Error: --install option requires 2 arguments!"
return 1
fi
source_media_ref="${parameters[0]}"
shift_array parameters
target_media_ref="${parameters[0]}"
;;
'--format')
# Limitation of ShellCheck to detect usage of indirection variables
# https://github.com/koalaman/shellcheck/wiki/SC2034
# shellcheck disable=SC2034
install_mode_ref='device'
shift_array parameters
if [ "${#parameters[@]}" -lt 2 ]; then
echo_with_color\
"red"\
"${FUNCNAME[0]}: Error: --format option requires 2 arguments!"
return 1
fi
source_media_ref="${parameters[0]}"
shift_array parameters
target_media_ref="${parameters[0]}"
;;
'--verbose'|'-v')
verbose='1'
;;
'--forGui')
no_color='1'
only_for_gui='1'
;;
'--no-color')
no_color='1'
;;
*)
printf "ERROR: Unknown command-line argument \"%s\"\n" "${parameters[0]}" >&2
return 1
;;
esac
shift_array parameters
done
if [ "${verbose}" = "1" ] && [ "${enable_debug}" != "Y" ]; then
trap 'trap_return "${FUNCNAME[0]}"' RETURN
trap 'trap_debug "${BASH_COMMAND}"' DEBUG
fi
if [ "${enable_debug}" = "Y" ]; then
set -o xtrace
fi
return 0
}; declare -fr process_commandline_parameters;
shift_array(){
util_check_function_parameters_quantity 1 "${#}"
local -n array_ref="${1}"
if [ "${#array_ref[@]}" -eq 0 ]; then
printf "ERROR: array is empty!\n" 1>&2
return 1
fi
# Unset the 1st element
unset "array_ref[0]"
# Repack array if element still available in array
if [ "${#array_ref[@]}" -ne 0 ]; then
array_ref=("${array_ref[@]}")
fi
return 0
}; declare -fr shift_array
trap_return(){
util_check_function_parameters_quantity 1 "${#}"
local returning_function="${1}"
for ignored_function in\
util_check_function_parameters_quantity\
util_is_parameter_set_and_not_empty\
switch_terminal_text_color\
echo_with_color; do
if [ "${returning_function}" == "${ignored_function}" ]; then
return 0
fi
done
echo_with_color green ""${FUNCNAME[0]}": INFO: returning from ${returning_function}\n" 1>&2
}; declare -fr trap_return
trap_debug(){
util_check_function_parameters_quantity 1 $#
local -r command_to_be_executed="${1}"
local -r command_base="${command_to_be_executed%% *}"
for ignored_command in util_check_function_parameters_quantity util_is_parameter_set_and_not_empty echo_with_color switch_terminal_text_color tput; do
if [ "${command_base}" = "${ignored_command}" ]; then
return 0
fi
done