#!/bin/bash
set -e

czu_ver=1.3

# create clonezilla usb (bios/uefi) with some tweaks / better defaults
# v1.3, ed <irc.rizon.net>, MIT-licensed, https://ocv.me/dev/clonezilla-usb.sh
#
# testing with qemu:
# truncate -s 256M test.hdd && echo ,,0c | sfdisk -q --label dos -w always test.hdd && mkfs.ext4 -E offset=1048576 -d testdata test.hdd
# truncate -s 2G cz.usb && ./clonezilla-usb.sh clonezilla-live-3.1.1-27-amd64.zip cz.usb y
# qemu-system-x86_64 -enable-kvm -cpu host -bios /usr/share/OVMF/OVMF_CODE.fd -device virtio-blk-pci,drive=cz,bootindex=1 -drive id=cz,if=none,format=raw,file=cz.usb -drive format=raw,discard=on,detect-zeroes=unmap,file=test.hdd -m 2048
#
# or build & test iso instead:
# ./clonezilla-usb.sh clonezilla-live-20231102-lunar-amd64.zip cz.iso && qemu-system-x86_64 -enable-kvm -cpu host -bios /usr/share/OVMF/OVMF_CODE.fd -cdrom cz.iso
#
# notes:
# * an existing clonezilla usb can be updated with a new clonezilla
#    version without losing the images on it by writing to /dev/sda2
#    rather than all of /dev/sda
# * to stream images over the network (ssh/nfs/smb/webdav), modify the
#    cmdline during boot by removing the last arg (ocsroot_src=local_dev)
# * bios / non-uefi support is default-disabled due to fear of potential
#    bugs in clonezilla's makeboot.sh which could nuke your hdd
# * only in the event that blockdev-names exactly match image definition
#    does clonezilla support images which cover multiple HDDs (limitation
#    in `create_temp_image_for_different_target_dev_name_if_necessary`)
# * if image checksum generation is too slow, remove -gb
# * if image checksum verification is too slow, remove -cm -cs -cb
# * if filesystem checksum generation is too slow, remove -gmf
# * if filesystem checksum verification is too slow, remove -cmf
#
# new in this version:
# * updated patch offsets for clonezilla 3.1.1-27 / 20231102
# * gracefully recover if some patches fail to apply
# * basic bios support for iso output (no isohdpfx, works in VMs);
#    the usb-img/dev outputs have better / full bios support
# * webdav-friendly image split size (1073=1GiB) because clonezilla
#    doesn't start uploading a chunk until it's done, keeping it in RAM
# * chmod images 644 instead of 600 (-noabo)
# * verify build deps present
# * more comments


# ----------------------------------------------------------------------
# -- config:

# repack initramfs and squashfs for 60% faster boot
# (some of the speed-boost is from removing unnecessary kernel modules,
#   but mainly it's changing compression from xz to zstd that does it)
optimize=1

# support non-uefi machines (set 1 to enable; default is uefi-only)
bios=

# clonezilla has uefi secureboot enabled by default;
# we disable it because it makes the debian edition fail to boot
secboot=


# -- end of config section
# ----------------------------------------------------------------------
zip="$1"
dev="$2"
yolo="$3"
[ "$optimize" = 1 ] || optimize=
[ "$secboot" = 1 ] || secboot=
[ "$bios" = 1 ] || bios=
die() { printf '%s\n' "$*"; exit 1; }

# print config summary before anything else
showcfg() {
	[ "$1" = 1 ] &&
		printf '\033[1;32menabled' && shift ||
		printf '\033[1;35mdisabled'
	printf '%s\033[0m\n' " $*"
}
showcfg $optimize optimization for faster boot
showcfg $bios bios / non-uefi support
showcfg $secboot secureboot support
echo

traps=
addtrap() {
	traps="$1; $traps"
	trap "$traps" INT TERM EXIT
}

[ $(id -u) -eq 0 ] || die need root

err=
[ -e "$zip" ] && printf '%s\n' "$zip" | grep -qiE "zip$" || {
	echo "need arg 1: clonezilla zip file, for example clonezilla-live-3.1.1-27-amd64.zip"
	[ "$zip" ] && die
	err=1
}
cz_ver="$(echo "$zip" | sed -r 's/-[^-]+$//;s/.*-live-//')"

# determine output format; iso / usb-image / usb-blockdev
iso=
[ "${dev##*.}" = iso ] && {
	echo "target is iso; building inside temp image file"
	yolo=y
	iso="$dev"
	dev=$(mktemp)
	truncate -s 515M $dev
	addtrap "rm $dev"
}
[ "$dev" ] && [ -e "$dev" ] && [ ! -b "$dev" ] && {
	echo "target is not a blockdevice; fixing with losetup"
	rmmod loop || true
	modprobe loop max_part=63
	dev=$(losetup -f --show "$dev")
	addtrap "losetup -d $dev"
}
printf '%s\n' "$dev" | grep -qE "^/dev/(sd[a-z]|loop[0-9])" || {
	echo "need arg 2: blockdevice to write, for example /dev/sdg or /dev/sdg2"
	echo "  (can also be an existing file, 515 MiB+, will create a usb image)"
	echo "  (can also be a .iso file, will be created, uefi-only)"
	err=1
}
[ $err ] && echo "optional arg 3: 'y' to skip yes/no checks" && die

# verify all deps are present
need() {
	command -v $1 >/dev/null && return
	echo -e "\033[1;31mERROR: required program '$1' is not available\033[0m"
	err=1
}
need mcopy
need mkfs.vfat
need mksquashfs
need unzip
[ "$iso" ] && need xorrisofs
[ -z "$iso" ] && [ $bios ] && need parted
[ $err ] && die

# figure out partition naming
dr=$dev
is_part=
echo $dev | grep -qE 'loop[0-9]p[0-9]|sd[a-z][0-9]' && is_part=1
[ $is_part ] && dr=$(echo $dev | sed -r 's/(sd[a-z]|loop[0-9]+).*/\1/')
if echo $dev | grep -q loop; then
	dp1=${dr}p1; dp2=${dr}p2
else
	dp1=${dr}1; dp2=${dr}2
fi
[ $is_part ] && [ $dev != $dp2 ] && die "must be whole device or the second partition (got $dev, want $dp2)"

# show a warning with some info about the target dev
lsblk $dev -o NAME,SIZE,TRAN,TYPE,MODEL,MOUNTPOINTS && echo
blkid $dev* && echo
echo "will destroy all data on the above target; confirm by pressing Y:"
# ask for confirmation unless 3rd argument is "y"
[ "$yolo" = y ] || {
	read -u1 -n1 -r; echo
	[ "$REPLY" = y ] || exit 1
}

# lets go
set -x
umount $dev* || true
[ $is_part ] || {
	# writing to an entire blockdevice; repartition it
	head -c $((1024*1024*2)) /dev/zero > $dr
	sz=$(lsblk $dr -nbo SIZE | awk 'NR==1{print int($1/(1024*1024))}')
	[ $bios ] && bootable=',*' || bootable=
	printf '%s\n' ,+$((sz-513))M,0c ",,ef$bootable" | sfdisk -q --label dos -w always $dr
	mkfs.vfat -S512 --mbr=n -nCZ_IMG $dp1 >/dev/null
}
# format the boot partition and unpack cz itself
mkfs.vfat -S512 --mbr=n -nCZ_BOOT $dp2 >/dev/null
td=$(mktemp -d)
td2=$(mktemp -d)
addtrap "[ -e $td2/m ] && umount $td2/m; umount $td; rmdir $td; rm -rf $td2"
mount $dp2 $td
excl=(
	live/freedos.img
	live/filesystem.squashfs
	boot/grub/i386-efi/\*
	boot/grub/unicode.pf2
	boot/grub/\*.png
	syslinux/\*.png
)
# skip secureboot stuff unless enabled
[ $secboot ] || excl+=(
	EFI/boot/boot\*
	boot/grub/efi.img
)
# ocs-live-dev (zip-builder) has deps on syslinux.exe and such, so keep them
unzip -q "$zip" -d $td -x "${excl[@]}"

is_ubuntu=$(awk 'NR==1&&/-[0-9]{8}-/{print 1}' $td/Clonezilla-Live-Version)

[ $is_ubuntu ] || [ ! $secboot ] ||
	printf "\033[1;37;41m\033[J\nWARNING: the debian edition of clonezilla (regular-stable, not alternative-stable) fails to boot on many machines! suggesting to either disable secureboot support or to use the ubuntu variant instead\n\033[0m\n"

[ $secboot ] ||
	mv $td/EFI/boot/{grub,boot}x64.efi  # debian secureboot-shim is busted; use grub directly

[ $bios ] && [ -z "$iso" ] && {
	# bios support is enabled;
	# fix some bugs before we use it
	patch $td/utils/linux/makeboot.sh <<'EOF'
@@ -90 +90 @@
-    read continue_choice 
+    read -n1 continue_choice 
@@ -100 +100 @@
-            echo "$msg_you_have_to_enter_yes_or_no!"
+            echo "$msg_you_have_to_enter_yes_or_no!"; continue_choice=
@@ -191 +191 @@
-  local RE2='i2o/hd[a-z]+[0-9]+'
+  local RE2='loop[0-9]+p[0-9]'
EOF
	[ "$yolo" = y ] && a=-b || a=
	(cd $td/utils/linux; ./makeboot.sh $a $dp2)
}

# repack initramfs for 2sec faster boot (27->25),
# repack squashfs for 8sec faster boot (25->17)
unzip -q "$zip" -d $td2 live/initrd.img live/filesystem.squashfs
if [ $optimize ]; then
	[ $is_ubuntu ] &&
		cp $td2/live/initrd.img $td/live/initrd.img ||
		xz -d < $td2/live/initrd.img | zstd --long -T0 -19 > $td/live/initrd.img &

	mkdir $td2/m
	mount $td2/live/filesystem.squashfs $td2/m
	(cd $td2/m && find -type d | cut -c3- | grep -E '/modules/.*/kernel.*/(wireless|bluetooth|mac80211|infiniband|sound|amdgpu|media|netfilter|ipv6)$|/espeak-ng') > $td2/e
	mksquashfs $td2/m $td/live/filesystem.squashfs -ef $td2/e -b 1024k -comp zstd -Xcompression-level 19 -exit-on-error
	umount $td2/m
	wait
	rm -rf $td2
else
	mv $td2/live/* $td/live/
fi

# set kernel args
cfg=(
	# don't ask about language
	locales=en_US.UTF-8

	# don't ask about keyboard layout
	keyboard-layouts=NONE

	# don't blank screen on exit
	ocs_screen_blank=no

	# apply additional hacks at runtime
	ocs_prerun=/run/live/medium/opt.sh

	# don't ask about bittorrent imaging
	ocs_live_type=device-image

	# always split created images at 1 GiB (for FAT32 and webdav)
	dcs_img_vol_limit=1073

	# assume images on local hdd; don't ask about ssh/nfs/smb/webdav
	# (can be temporarily disabled by removing it from boot menu)
	ocsroot_src=local_dev
)
tf1=$(mktemp)
tf2=$(mktemp)
tf3=$(mktemp)
cat $td/boot/grub/grub.cfg >$tf1
cat $td/syslinux/syslinux.cfg >$tf2 || true
cat $td/syslinux/isolinux.cfg >$tf3 || true
for kv in "${cfg[@]}"; do
	IFS== read k v <<<$kv
	for tf in $tf1 $tf2 $tf3; do
		sed -ri "s& $k=[^ ]* ?& &; s&( boot=live .*)&\1 $k=$v&" $tf
	done
done
# for tf in $tf1 $tf2 $tf3; do sed -ri 's/ quiet loglevel=0 / /' $tf; done  # debug
[ $is_ubuntu ] && color=magenta || color=cyan
sed -ri 's`^play .*`play 1920 330 1 0 2 330 1`; s`cyan/blue`'$color'/black`; s`^(set timeout=").*`\12"`' $tf1
for tf in $tf2 $tf3; do
	sed -ri 's`\x07``; /MENU (BACKGROUND|COLOR)/d; s`^(timeout )[0-9]+`\120`' $tf
done
for tf in $tf1 $tf2 $tf3; do
	sed -ri "s/Clonezilla live \(/czusb-$czu_ver (/g" $tf
done
cat $tf1 > $td/boot/grub/grub.cfg
cat $tf2 > $td/syslinux/syslinux.cfg || true
cat $tf3 > $td/syslinux/isolinux.cfg || true
rm $tf1 $tf2 $tf3

# hack the stuff that can't be done the right way
# ======================================================================
(
[ $is_ubuntu ] && color=5 || color=4
cat <<OPT_EOF
#!/bin/bash
set -eu

# print cloenzilla version in top-right corner
printf '\033[s\033[1;37;4${color}m\033[1;999H\033[${#cz_ver}D\033[C$cz_ver\033[2;999H\033[6Dczu-$czu_ver\033[0m\033[u'
OPT_EOF
cat <<'OPT_EOF'

mkdir /dev/shm/sbak
cp -p /usr/sbin/ocs-{sr,prep-repo,live-bind-mount} /usr/share/drbl/sbin/{ocs,drbl}-functions /dev/shm/sbak/

apatch() { patch -s $1 || mv $1.orig $1; }

# assume USB devices are already present, don't wait
apatch /usr/sbin/ocs-prep-repo <<'EOF'
@@ -42,2 +42,3 @@
           --msgbox "$msg_prompt_for_insert_USB_dev_if_necessary" 0 0
+   elif true; then true
    else
@@ -72,2 +73,3 @@
    # Question about fsck the repo partition.
+   echo fsck-y >$ANS_TMP ||
    $DIA --backtitle "$msg_nchc_free_software_labs" --title \
EOF

# 1) confirm_before_clone is funky
# 2) prefer CZ_IMG (first flashdrive partition) for images
# 3) skip TTY1 activity confirmation prompt since ttyS0 is disabled
# 4) prevent accidental automatic fsck of btrfs
apatch /usr/share/drbl/sbin/ocs-functions <<'EOF'
@@ -3739 +3739 @@
-  if [ "$confirm_before_clone" = "yes" ]; then
+  if false; then
@@ -3831 +3831 @@
-  if [ "$confirm_before_clone" = "yes" ] && [ "$rest_conf" = "yes" ]; then
+  if false; then
@@ -4963,4 +4963,6 @@
     while [ "$ASK_INPUT" -eq 1 ]; do
+      local defsrc=$(df /run/live/medium/ --output=source | awk '/2$/{d=$1} END{sub(/.*\//,"",d);sub(/2/,"1",d);print d}')
+      [ -e "/dev/$defsrc" ] || defsrc=$(blkid | awk -F: '/"CZ_IMG"/{sub(/.*\//,"");print$1;exit}')
       $DIA --backtitle "$msg_nchc_free_software_labs" --title "$msg_nchc_clonezilla | $msg_mode: $ocs_mode_prompt" \
-        --$selection "$msg_choose_dev_to_what" 0 0 $height $HARDDEVS \
+        --$selection "$msg_choose_dev_to_what" 0 0 $height --default-item "$defsrc" $HARDDEVS \
       2> $TMP
@@ -11499,4 +11501,5 @@
   TMP="$(mktemp /tmp/ocslivemode.XXXXXX)"
   trap "[ -f "$TMP" ] && rm -f $TMP" HUP INT QUIT TERM EXIT
+  echo Start_Clonezilla >$TMP ||
   $DIA --backtitle "$msg_nchc_free_software_labs" --title  \
   "$msg_start_clonezilla" --menu "$msg_start_clonezilla_or_enter_shell\n$msg_choose_mode:" \
@@ -12130 +12133 @@
-	  echo "Running: $btrfs_chk"
+	  echo "too dangerous to run: $btrfs_chk"; return
EOF

# mount top of filesystem for images, don't browse
apatch /usr/sbin/ocs-live-bind-mount <<'EOF'
@@ -137,2 +137 @@
-  BrowseCurrentDirectory "$pre_ocsroot_path" $sel_dir
-  real_ocsroot="$(cat $sel_dir)"
+  real_ocsroot="$pre_ocsroot_path"
EOF

# skip fatresize because it is scary
apatch /usr/sbin/ocs-resize-part <<'EOF'
@@ -96,2 +96,3 @@
    vfat|fat16|fat32)
+              echo "will not fatresize $partition"; exit 1
               if ! command -v fatresize&> /dev/null; then
EOF

# skip pointless pauses
apatch /usr/sbin/ocs-sr <<'EOF'
@@ -887,4 +887,3 @@
     if [ "$ocs_batch_mode" != "on" ]; then
-      echo -n "$msg_press_enter_to_continue "
-      read
+      true
     fi
EOF
sed -ri 's/(countdown )[0-9]+$/\13/' /usr/sbin/ocs-live-final-action 

# better defaults
apatch /usr/share/drbl/sbin/drbl-functions <<'EOF'
@@ -1485,3 +1485,3 @@
   "$msg_mode: $ocs_mode_prompt" --menu "$msg_choose_post_mode_after_clone_1:" \
-  0 0 0 $DIA_ESC \
+  0 0 0 --default-item '-p poweroff ' $DIA_ESC \
   "-p choose "    "$msg_ocs_param_p_choose_1" \
@@ -1816,3 +1816,3 @@
       "$msg_clonezilla_advanced_extra_param | $msg_mode: $ocs_mode_prompt" --menu "$msg_choose_if_fsck_the_source_part" \
-      0 0 0 $DIA_ESC \
+      0 0 0 --default-item '-fsck-y ' $DIA_ESC \
       " "     "$msg_skip_check_source_fs" \
@@ -1883,3 +1883,3 @@
       "$msg_clonezilla_advanced_extra_param | $msg_mode: $ocs_mode_prompt" --menu "$msg_choose_one_compression_param_to_save" \
-      0 0 0 $DIA_ESC \
+      0 0 0 --default-item "${ocs_z9p_option_1:--z1p}" $DIA_ESC \
       "-z1p"     "$msg_ocs_param_z1p" \
@@ -1911,3 +1911,3 @@
         "$msg_clonezilla_advanced_extra_param | $msg_mode: $ocs_mode_prompt" --menu "$msg_choose_one_compression_param_to_save" \
-        0 0 0 $DIA_ESC \
+        0 0 0 --default-item "${ocs_z9p_option_1:--z1p}" $DIA_ESC \
         "-z1p"              "$msg_ocs_param_z1p" \
@@ -2122,3 +2122,3 @@
     "$msg_clonezilla_advanced_extra_param | $msg_mode: $ocs_mode_prompt" --menu "$msg_choose_if_checking_image_restorable_before_restoring" \
-    0 0 0 $DIA_ESC \
+    0 0 0 --default-item '-scr ' $DIA_ESC \
     " "     "$msg_ocs_param_check_img_restorable_before_restoring" \
@@ -2233,3 +2233,3 @@
       "$msg_clonezilla_advanced_extra_param | $msg_mode: $ocs_mode_prompt" --menu "$msg_choose_one_compression_param_to_save" \
-      0 0 0 $DIA_ESC \
+      0 0 0 --default-item "${ocs_z9p_option_1:--z1p}" $DIA_ESC \
       "-z1p"           "$msg_ocs_param_z1p" \
@@ -2259,3 +2259,3 @@
         "$msg_clonezilla_advanced_extra_param | $msg_mode: $ocs_mode_prompt" --menu "$msg_choose_one_compression_param_to_save" \
-        0 0 0 $DIA_ESC \
+        0 0 0 --default-item "${ocs_z9p_option_1:--z1p}" $DIA_ESC \
         "-z1p"              "$msg_ocs_param_z1p" \
@@ -2274,3 +2274,3 @@
       "$msg_clonezilla_advanced_extra_param | $msg_mode: $ocs_mode_prompt" --menu "$msg_choose_one_compression_param_to_save" \
-      0 0 0 $DIA_ESC \
+      0 0 0 --default-item "${ocs_z9_option_1:--z1}" $DIA_ESC \
       "-z1"            "$msg_ocs_param_z1" \
@@ -2293,3 +2293,3 @@
         "$msg_clonezilla_advanced_extra_param | $msg_mode: $ocs_mode_prompt" --menu "$msg_choose_one_compression_param_to_save" \
-        0 0 0 $DIA_ESC \
+        0 0 0 --default-item "${ocs_z9_option_1:--z1}" $DIA_ESC \
         "-z1"              "$msg_ocs_param_z1" \
@@ -2329,3 +2329,3 @@
     "$msg_clonezilla_advanced_extra_param | $msg_mode: $ocs_mode_prompt" --menu "$msg_choose_if_fsck_the_source_part" \
-    0 0 0 $DIA_ESC \
+    0 0 0 --default-item '-fsck-y ' $DIA_ESC \
     "-sfsck "  "$msg_skip_check_source_fs" \
EOF

# don't ask about encryption
echo encrypt_ocs_img=-senc >> /etc/ocs/ocs-live.conf 

# 1) show progressbar for checksum operations (a bit buggy)
# 2) ignore drive-names shuffling between reboots (the OS should use UUIDs anyways)
# 3) stop cz from overwriting itself when restoring to "1st-disk"
# 4) if filesystem cant be mounted to checksum all files within, just ignore it (system-reserved-partition)
# 5) prevent oom by only logging files with invalid checksums
# 6) always assume images should fit on fat32
apatch /usr/share/drbl/sbin/ocs-functions <<'EOF'
@@ -45,2 +45,3 @@
       echo "Generating $out_f for image $target_dir. This might take a while..."
+      (sleep 0.2; pv -bartpd $(pidof $imtd || (sleep 0.3 && pidof $imtd))) &
       (cd $img_dir; time $imtd * > $out_f)
@@ -87,2 +88,3 @@
         echo "Checking $out_f for image $img_dir. This might take a while..."
+        (sleep 0.2; pv -bartpd $(pidof $imtd || (sleep 0.3 && pidof $imtd))) &
         (cd $img_dir; LC_ALL=C $imtd -c $out_f)
@@ -8750,5 +8752,5 @@
   echo "$msg_restored_OS_change_fstab_grub_conf"
   [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
-  if [ "$ocs_batch_mode" != "on" ]; then
+  if false; then
     echo -n "$msg_press_enter_to_continue..."
     read
@@ -9568 +9570 @@
-    target_hd="$(get_disk_list $partition_table | sed -r -e "s/loop[[:digit:]]*//" | awk -F" " '{print $1}')"
+    target_hd="$( (get_not_busy_disks_or_parts harddisk >/dev/null 2>&1; echo $dev_list) | sed -r -e "s/loop[[:digit:]]*//" | awk -F" " '{print $1}')"
@@ -14343,5 +14345,5 @@
     echo "$msg_unsble_to_create_checksum_file" | tee --append ${OCS_LOGFILE}
     [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
-    if [ "$ocs_batch_mode" != "on" ]; then
+    if false; then
       echo -n "$msg_press_enter_to_continue..."
       read
@@ -14395 +14395 @@
-      | tee --append ${OCS_LOGFILE} | cat - > /var/log/$(to_filename ${sum_part})-${chksum_cmd}-results.log
+      | grep -v ': OK$' | tee -a $OCS_LOGFILE /var/log/$(to_filename $sum_part)-${chksum_cmd}-results.log - | awk 'NR<9'
@@ -16082,5 +16084,5 @@
        [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
-       export VOL_LIMIT_IN_INTERACTIVE="4096"
        ;;
   esac
+       export VOL_LIMIT_IN_INTERACTIVE="1073"
 } # end of check_if_repo_fat_tune_image_vol_limit
EOF

apatch /usr/share/drbl/sbin/drbl-functions <<'EOF'
@@ -1630 +1630 @@
-      "-nogui"   "$msg_ocs_param_nogui" off \
+      "-nogui"   "$msg_ocs_param_nogui" on \
@@ -1647 +1647 @@
-      "-icds"    "$msg_ocs_param_icds" off \
+      "-icds"    "$msg_ocs_param_icds" on \
@@ -1651,4 +1651,4 @@
-      "-cm"      "$msg_ocs_param_cm" off \
-      "-cs"      "$msg_ocs_param_cs" off \
-      "-cb"      "$msg_ocs_param_cb" off \
-      "-cmf"     "$msg_ocs_param_cmf" off \
+      "-cm"      "$msg_ocs_param_cm" on \
+      "-cs"      "$msg_ocs_param_cs" on \
+      "-cb"      "$msg_ocs_param_cb" on \
+      "-cmf"     "$msg_ocs_param_cmf" on \
@@ -1661 +1661 @@
-      "-srel"    "$msg_ocs_param_srel" off \
+      "-srel"    "$msg_ocs_param_srel" on \
@@ -1671 +1671 @@
-        echo "-g auto" "-e1 auto" "-e2" "-r" "-x" "-j2" >> $OCS_PARAM_TMP
+        echo "-g auto -e1 auto -e2 -nogui -r -x -j2 -icds -cm -cs -cb -cmf -srel " >> $OCS_PARAM_TMP
@@ -1677 +1677 @@
-        echo "-e1 auto" "-e2" "-t" "-r" "-x" >> $OCS_PARAM_TMP
+        echo "-e1 auto -e2 -nogui -t -r -x -cm -cs -cb -cmf -srel " >> $OCS_PARAM_TMP
@@ -1790 +1790 @@
-      "-nogui "    "$msg_ocs_param_nogui" off \
+      "-nogui "    "$msg_ocs_param_nogui" on \
@@ -1800,3 +1800,3 @@
-      "-gb "       "$msg_ocs_param_gb" off \
-      "-gmf "      "$msg_ocs_param_gmf" off \
-      "-noabo "    "$msg_ocs_param_noabo" off \
+      "-gb "       "$msg_ocs_param_gb" on \
+      "-gmf "      "$msg_ocs_param_gmf" on \
+      "-noabo "    "$msg_ocs_param_noabo" on \
@@ -1811 +1811 @@
-      echo "-j2 " >> $OCS_PARAM_TMP
+      echo "-j2 -nogui -noabo -gb -gmf " >> $OCS_PARAM_TMP
@@ -2017 +2017 @@
-    "-nogui"   "$msg_ocs_param_nogui" off \
+    "-nogui"   "$msg_ocs_param_nogui" on \
@@ -2022 +2022 @@
-    "-c"       "$msg_ocs_param_c" on \
+    "-c"       "$msg_ocs_param_c" off \
@@ -2034 +2034 @@
-    "-icds"    "$msg_ocs_param_icds" off \
+    "-icds"    "$msg_ocs_param_icds" on \
@@ -2038,4 +2038,4 @@
-    "-cm"      "$msg_ocs_param_cm" off \
-    "-cs"      "$msg_ocs_param_cs" off \
-    "-cb"      "$msg_ocs_param_cb" off \
-    "-cmf"     "$msg_ocs_param_cmf" off \
+    "-cm"      "$msg_ocs_param_cm" on \
+    "-cs"      "$msg_ocs_param_cs" on \
+    "-cb"      "$msg_ocs_param_cb" on \
+    "-cmf"     "$msg_ocs_param_cmf" on \
@@ -2045 +2045 @@
-    "-srel"    "$msg_ocs_param_srel" off \
+    "-srel"    "$msg_ocs_param_srel" on \
@@ -2061 +2061 @@
-      echo "-g auto" "-e1 auto" "-e2" "-r" "-j2" "$opt_confirm_" >> $OCS_PARAM_TMP
+      echo "-g auto -e1 auto -e2 -nogui -r -j2 -icds -cm -cs -cb -cmf -srel $opt_confirm_ " >> $OCS_PARAM_TMP
@@ -2067 +2067 @@
-      echo "-e1 auto" "-e2" "-t" "-r" "$opt_confirm_" >> $OCS_PARAM_TMP
+      echo "-e1 auto -e2 -nogui -t -r -icds -cm -cs -cb -cmf -srel $opt_confirm_ " >> $OCS_PARAM_TMP
@@ -2164 +2164 @@
-    "-c "       "$msg_ocs_param_c" on \
+    "-c "       "$msg_ocs_param_c" off \
@@ -2166 +2166 @@
-    "-nogui "   "$msg_ocs_param_nogui" off \
+    "-nogui "   "$msg_ocs_param_nogui" on \
@@ -2174,3 +2174,3 @@
-    "-gb "      "$msg_ocs_param_gb" off \
-    "-gmf "     "$msg_ocs_param_gmf" off \
-    "-noabo "   "$msg_ocs_param_noabo" off \
+    "-gb "      "$msg_ocs_param_gb" on \
+    "-gmf "     "$msg_ocs_param_gmf" on \
+    "-noabo "   "$msg_ocs_param_noabo" on \
@@ -2183 +2183 @@
-    echo "-c " "-j2 " >> $OCS_PARAM_TMP
+    echo "-j2 -nogui -noabo -gb -gmf " >> $OCS_PARAM_TMP
EOF

# enable this to build recovery iso/zip which does not ask for confirmation before overwriting HDD
if false; then
apatch /usr/share/drbl/sbin/drbl-functions <<'EOF'
--- drbl-functions	2023-08-24 21:24:50.869765410 +0000
+++ a	2023-08-24 21:27:26.773760624 +0000
@@ -2041,3 +2041,3 @@
   else
-    if [ "$ocs_batch_mode" != "on" ]; then
+    if false; then
       # Interactive mode. We need to add "-c"
EOF
fi

# enable this if something goes wrong and clonezilla fills your screen with garbage before you're able to see what
#for d in /usr/*bin /usr/share/drbl; do find $d -xdev -type f | grep -E 'ocs|drbl|nezil' | xargs grep -lIE '^USAGE\(\) \{$' -- | while IFS= read -r f; do sed -ri 's/^(USAGE\(\) \{)$/\1 echo "usage follows..."; sleep 2;/' "$f"; done; done

# better zstd compression (1=live, 2=convert)
sed -ri 's/\$extra_zstdmt_opt/--long -7/' /usr/sbin/ocs-sr
sed -ri 's/\$extra_zstdmt_opt/--long -19/' /usr/sbin/ocs-cvtimg-comp

# allow sysrq
echo 1 > /proc/sys/kernel/sysrq

OPT_EOF
)>$td/opt.sh
# ======================================================================

cp "$0" $td/

[ $secboot ] || {
	# secureboot is not enabled;
	# build new efi.img since ocs-iso needs it
	eimg=$td/boot/grub/efi.img
	sz=$(wc -c <$td/EFI/boot/bootx64.efi | awk '{print int($1/1024)+96}')
	rm -f $eimg
	touch $eimg
	truncate -s ${sz}k $eimg
	mkfs.vfat -F12 -nESP $eimg
	mmd -i $eimg ::EFI ::EFI/boot ::/boot ::/boot/grub
	mcopy -Qbmsi $eimg -s "$td/EFI/boot/bootx64.efi" ::/EFI/boot/bootx64.efi
	mcopy -Qbmsi $eimg -s "$td/boot/grub/grub.cfg"   ::/boot/grub/grub.cfg
}

if [ "$iso" ]; then
	args=(
		-output "$iso"
		-full-iso9660-filenames
		-joliet
		-rational-rock
		-sysid LINUX
		-volid cz_iso
	)
	[ $bios ] && args+=(
		-eltorito-boot syslinux/isolinux.bin
		-eltorito-catalog syslinux/boot.cat
		-no-emul-boot
		-boot-load-size 4
		-boot-info-table
	)
	args+=(
		-eltorito-alt-boot
		-e boot/grub/efi.img
		-no-emul-boot
		-isohybrid-gpt-basdat
		-follow-links
		-file-mode 0755
		$td/
	)
	xorrisofs "${args[@]}"
else cat <<'EOF'

almost done -- writing to disk...
wait until prompt appears before unplugging the USB flashdrive:

EOF
fi
