#!/bin/bash

#! /bin/bash
#
# Copyright 2022 Nio Wiklund
#
# GPLv3: GNU GPL version 3
# <http://gnu.org/licenses/gpl.html>.
#
# This is free software: you are free to change and redistribute it.
# There is NO WARRANTY, to the extent permitted by law.
#-----------------------------------------------------------------------------
# author sudodus alias nio-wiklund at launchpad
#
# date        editor   comment
# 2022-05-08  sudodus  created
# 2022-05-08  sudodus  version 0.0.1
# 2022-05-08  sudodus  version 0.0.2
# 2022-05-10  sudodus  version 22.0.0
# 2022-05-11  sudodus  version 22.0.1 the first published version
# 2022-05-15  sudodus  added optional parameter #6 'boot-flag'
#                      in readparams, addparts
#                      plus extra warnings when large target drives
# 2022-05-15  sudodus  version 22.0.2
# 2022-05-17  sudodus  copyiso: sleep to settle down to get syslbl
# 2022-05-17  sudodus  version 22.0.3
# 2022-05-20  sudodus  add_parts: if statement for boot-flag
#                      also when live-only (alias not persistent)
# 2022-05-20  sudodus  version 22.0.5
# 2022-05-23  sudodus  read_params: warning and question if the
#                      source is not an Ubuntu [flavour] iso file
#                      p_zentest and p_checkpoint called from read_params
# 2022-05-23  sudodus  version 22.0.6
# 2022-06-03  sudodus  read_params, p_checkpoint: fine-tuned output to
#                      terminal window
# 2022-06-03  sudodus  version 22.0.7
# 2022-08-26  sudodus  syslbl="Not Ubuntu 19." when not Ubuntu
# 2022-08-26  sudodus  version 22.0.8
# 2022-09-13  sudodus  redbacks when errors causing exit
# 2022-09-13  sudodus  version 22.1.1
# 2023-02-07  sudodus  increased size of partition for iso file 5G --> 7G
# 2023-02-07  sudodus  version 23.0.1
# 2023-04-21  sudodus  read_params, tweak_grub: check for 'layerfs' in grub
#                      in the iso file, when found modify the linux-line
#                      to match the boot structure of the new installer
# 2023-04-21  sudodus  version 23.1.0
# 2023-05-13  sudodus  read_params: minor fix to improve output when target
#                      drive size >= 128GB
# 2023-05-13  sudodus  version 23.1.2
# 2023-10-20  sudodus  new template with grub 2.12-rc1 (replacing 2.0.6)
#                      new grub menuentries: 'live-only with toRAM' and
#                      new memtest86+ v6.20 that works also in UEFI mode
# 2023-10-20  sudodus  version 23.2.0

version="${0##*/} 23.2.0"

inversvid="\0033[7m"
resetvid="\0033[0m"
faintvid="\0033[2m"
redback="\0033[1;37;41m"
greenback="\0033[1;37;42m"
blueback="\0033[1;37;44m"
logoansi="\0033[38;5;0;48;5;148m"
logorgb="'#afd700'"

starttim=
source=
target=
pt=
grv=
persistent=
syslbl=
bflag=false
msiz=100
manager=
layerfs=false
bar="-------------------------------------------------------------------------------"

########################################################################

function read_params {

if [ "$1" == "-v" ]
then
 echo "$version"
 exit
fi 

if [ "$(whoami)" != "root" ] || [ "$HOME" != "/root" ] || [ "$1" == "-h" ]
then
 echo -e "Usage:
${inversvid}sudo -H ${0##*/} <source> <target> <part-tbl> <grub-ver> <persistent or live-only> [boot-flag]$resetvid
Examples:
sudo -H ${0##*/} lubuntu-22.04-desktop-amd64.iso /dev/sdc gpt   grub-new persistent
sudo -H ${0##*/} xubuntu-22.04-desktop-amd64.iso /dev/sdc msdos grub-new persistent boot-flag
param 1: source file
param 2: target drive
param 3: partition table: gpt or msdos
param 4: grub version: grub-new or grub-2.0.4
param 5: persistent or live-only
param 6: boot-flag [or blank] (for HP from ~ 2010)
Help: 
${0##*/} -h
Version:
${0##*/} -v
${inversvid}Available drives $resetvid"
 lsblk -do name,size,tran,model | \
  grep -v -e 'sr[0-9]' -e 'fd[0-9]' -e 'zram[0-9]' -e 'loop[0-9]'
 exit
fi

echo -e "$inversvid $version $resetvid"
starttim=$(date '+%s')
echo "start [$version] @ $(date --date="@$starttim" '+%F %X')"

# select iso file

if [ "$1" == "" ] || [ "$1" == "${1/.iso}" ]
then
 echo -e "$redback iso file should be specified by first parameter $resetvid"
 exit 1
elif test -s "$1"
then
 source="$1"
 echo -e "$inversvid source file: $resetvid"
 ls "$source"
else
 echo -e "$redback $1 is not a real iso file (should specify the source file) $resetvid"
 exit 1
fi
tmp=$(grep '/dev/loop' /etc/mtab | grep iso9660 | sed 's/ .*//' | tail -n1)
if [ "$tmp" != "" ]
then
 umount "$tmp"
fi
mntpt=$(mktemp -d --tmpdir dus.XXXXXXXXXX)
mount -o loop "$source" "$mntpt"
sleep 1

if grep 'layerfs-path' "$mntpt"/boot/grub/grub.cfg
then
 layerfs=true
fi 
echo "layerfs=$layerfs" #############

syslbl=$(lsblk -o label,mountpoint | grep "$mntpt"|sed "s% *$mntpt%%")
umount "$mntpt"
sleep 1
if [ "${syslbl/buntu}" == "$syslbl" ]
then
 syslbl="Not Ubuntu 19."
 echo -e "$redback
 This is not an Ubuntu or Ubuntu flavour iso file. It might be too different
 to boot via the 'grub-n-iso' alias 'isoboot' method used by '${0##*/}'.
 Try 'cloning' if live or 'dus-persistent' if persistent!$resetvid"
 echo -en "$redback$inversvid Do you want to go ahead with '${0##*/}' anyway? (y/N)$resetvid "
 read nobuntu
 if [ "$nobuntu" != "y" ]
 then
#  umount "$mntpt"
  exit 1
 fi
fi

# select target drive ( >= 4GB )
# check target drive and show lsblk of it

if [ "$2" == "" ]
then
 echo -e "$redback target drive should be specified by second parameter $resetvid"
 exit 1
elif test -b "$2"
then
 gb=$(( ($(lsblk -bdno size "$2") + 200000000 )/1000000000 ))
 echo -en "$inversvid target drive: size = $gb GB $resetvid"
 if [ "$gb" -ge "128" ]
 then
  echo -e "$redback
-------------------------------------------------------------------
 $2 is >= 128 GB; Warning: Is this the correct drive?
-------------------------------------------------------------------$resetvid"
 elif [ "$gb" -ge "60" ]
 then
  echo -e "$redback $2 is >= 60 GB; please double-check $resetvid"
 else
  echo ""
 fi
 if [ "$gb" -ge "4" ]
 then
  target="$2"
  lsblk -do model,name "$target"
#  echo -e "$blueback"
#  lsblk -o model,name,fstype,label,size,mountpoint "$target"
#  echo -e "$resetvid"
 else
  echo -e "$redback $2 is too small, < 4 GB $resetvid"
  exit 1
 fi
else
 echo -e "$redback $2 is not a block device (should specify the target drive) $resetvid"
 exit 1
fi

# select and extract template
#  GPT or MSDOS partition table
#  grub 2.0.4 or new version

if [ "$3" == "" ]
then
 echo -e "$redback partition table should be specified by third parameter $resetvid"
 exit 1
elif [ "${3,,}" == "gpt" ]
then
 pt="${3,,}"
 echo -e "$inversvid partition table: $resetvid"
 echo "$pt"
elif [ "${3,,}" == "msdos" ]
then
 pt="${3,,}"
 echo -e "$inversvid partition table: $resetvid"
 echo "$pt"
else
 echo -e "$redback $3 is neither 'gpt' nor 'msdos' $resetvid"
 exit 1
fi

if [ "$4" == "" ]
then
 echo -e "$redback grub version should be specified by fourth parameter $resetvid"
 exit 1
elif [ "$4" == "grub-2.0.4" ] || [ "$4" == "grub-new" ]
then
 grv="$4"
 echo -e "$inversvid grub version: $resetvid"
 echo "$grv"
else
 echo -e "$redback $4 is not an available version $resetvid"
 exit 1
fi

# select persistent live or live-only drive
#  check if size is enough for persistent live drive

if [ "$5" == "" ]
then
 echo -e "$redback 'persistent' or 'live-only' should be specified by fifth parameter $resetvid"
 exit 1
elif [ "$5" == "persistent" ]
then
 persistent=true
 if [ "$gb" -ge "8" ]
 then
  echo -e "$inversvid persistent drive: $resetvid"
  echo "$2 is big enough for a persistent live drive, $gb GB"
 else
  echo -e "$redback $2 is too small for a persistent live drive, < 8 GB $resetvid"
  exit 1
 fi
elif [ "$5" == "live-only" ]
then
 persistent=false
 echo -e "$inversvid live-only drive: $resetvid"
else
 echo -e "$redback $5 is neither 'persistent' nor 'live-only' $resetvid"
 exit 1
fi

# optional boot-flag

if [ "$6" == "boot-flag" ]
then
 bflag=true
 echo -e "$inversvid boot-flag set $resetvid"
elif [ "$6" != "" ]
then
 echo -e "$redback $5 parameter 6: should be 'boot-flag' or blank (no sixth parameter) $resetvid"
 exit 1
fi

# Final checkpoint

echo -e "$bar
$inversvid Final checkpoint: $resetvid
$bar"
p_zentest
p_checkpoint "Prepare $inversvid $5 $resetvid system from
'$source'
to the target device (drive) '$target'"
if [ $? -ne 0 ]
then
 echo -e "$redback ${0##*/} terminated by user $resetvid"
 exit 1
fi
}
########################################################################

function p_checkpoint {

# $text string with high-lights

 ans=
 q_chk="Final checkpoint, go ahead?"
 q_ch2="Final checkpoint:
are you ready?"
  
 echo -en "$1"
 action="${1/\\*7m}"
 action="${action/\\*0m}"
 action=$(echo "$action"|sed "s#^'/.*/#'#")
 blklist=$(lsblk -o MODEL,NAME,FSTYPE,LABEL,SIZE "$target")
 echo -e "$blueback"
 lsblk -lo MODEL,NAME,FSTYPE,LABEL,SIZE "$target"
 echo -e "$resetvid"
 trgtxt=$(lsblk -o NAME,SIZE,MODEL -d "$target")
 trgtx1=$(echo "$trgtxt"|head -n1)
 trgtx2=$(echo "$trgtxt"|tail -n1)
 trgtxt="${trgtxt,,}"
 if [ "$manager" == "z" ]
 then
  ans=$(zenity --list --radiolist \
  --width=$((msiz * 960 / 100)) --height=$((msiz * 560 / 100)) \
  --title="$version - $q_chk" --cancel-label="Stop" --ok-label="Go" \
  --window-icon="/usr/share/icons/hicolor/48x48/apps/mkusb.png" \
  --text="Source: '$source'
Target: '$target'
<tt>
$blklist
</tt>" \
  --column="Go/Stop" --column="$action" --column="$trgtxt"\
  true Stop "No, I am not sure yet" \
  false Go  "Yes, I want to go ahead" \
  2> /dev/null)
  if [ $? -ne 0 ]
  then
   ans=n
  fi
 elif [ "$manager" == "d" ]
 then
  action="$trgtx1\n$trgtx2\n$action\n\Z1***** $q_chk *****\Zn"
  ans=$(dialog --no-collapse \
 --backtitle "$version - $q_chk" \
 --cancel-label "Stop" --ok-label "Go" --colors \
 --defaultno \
 --radiolist "$action" 0 0 0 \
 Stop "\Z1No, I am not sure yet\Zn" on \
 Go   "Yes, I want to go ahead" off \
 3>&1 1>&2 2>&3 3>&-)
  if [ $? -ne 0 ]
  then
   ans=n
  fi
 else
  echo -en "$redback $q_chk (g/N) $resetvid"
  read ans
  if [ "$ans" == "g" ]
  then
   echo -en "$redback Are you sure ? (y/N) $resetvid"
   read an2
   if [ "$an2" != "y" ]
   then
    return 1
   fi
  fi
 fi
 
 if [ "$ans" == "Go" ]
 then
  ans=g
 elif [ "$ans" == "Stop" ]
 then
  ans=n
 fi
 if [ "$ans" == "g" ]
 then
  return 0
 else
  if [ "$manager" == "z" ]
  then
   src_orig=
  fi
  return 1
 fi
}
#######################################################################

function p_zentest {

zenity --info --title="$version - zenity-test" --timeout 1 \
 --width=350 --height=150 \
--text="Checking if zenity works in this environment" > /dev/null 2>&1
exitnr=$?
if [ $exitnr -eq 0 ] || [ $exitnr -eq 5 ]
then
 manager=z
else
 return 1
fi
}
########################################################################

function get_tmplt {

# select and extract template
#  GPT or MSDOS partition table
#  grub 2.0.4 or new version

if [ "$pt" == "gpt" ] && [ "$grv" == "grub-new" ]
then
 template=/usr/share/mkusb/dd_grub-boot-template-for-uefi-n-bios_grub-new.img.xz
elif [ "$pt" == "gpt" ] && [ "$grv" == "grub-2.0.4" ]
then
 template=/usr/share/mkusb/dd_grub-boot-template-for-uefi-n-bios_grub-2.0.4.img.xz
elif [ "$pt" == "msdos" ] && [ "$grv" != "grub-new" ]  # maybe modify this
then
 template=/usr/share/mkusb/dd_grub-boot-template-for-uefi-n-bios_msdos_grub-2.0.2-n-2.0.4.img.xz
else
 echo -e "$redback no grub-boot-template$resetvid was found for this
combination of partition table and grub version"
 exit 1
fi
echo "template: $template"
umount "$target"*
gpt_zap "$target"
xzcat "$template" > "$target"
if [ $? -ne 0 ]
then
 echo -e "$redback template extraction failed :-( $resetvid"
 exit 1
fi
sleep 2
partprobe
sleep 1
if [ "$pt" == "gpt" ];then gpt_fix "$target";fi
sync
echo "template extracted to target"
}
########################################################################

function gpt_fix {

# $1 is the target device

echo \
"v
q" \
| gdisk "$1" 2>/dev/null |grep -e 'GPT: damaged' -e 'Problem:' > /dev/null 2>&1
if [ $? -eq 0 ]
then
 echo \
"v
x
e
r
d
w
y" \
| gdisk "$1" > /dev/null 2>&1

 echo \
"v
q" \
| gdisk "$1" 2>/dev/null |grep -e 'GPT: damaged' -e 'Problem:' > /dev/null 2>&1
 if [ $? -eq 0 ]
 then
  echo "gpt_fix: failed to fix the GUID partition table (GPT) of $1"
 else
  echo "gpt_fix: done :-)"
 fi
else
 echo "gpt_fix: checked :-)"
fi
}
########################################################################

function gpt_zap {

# $1 is the target device

echo \
"
x
z
y
y" \
| gdisk "$1" > /dev/null 2>&1

echo "gpt_zap: done"
}
########################################################################

function add_parts {

# add partitions

if $persistent
then
 endp=$(( $(lsblk -bdno size "$target")/512-524288 )) # End - 256M
# echo "endp=$endp"

 if [ "$pt" == "gpt" ]
 then
  if $bflag
  then
   echo "optional parameter 6 'boot-flag' ignored when 'gpt'"
  fi
  echo \
"- 7G
$endp
- -
quit
y" | sfdisk --append "$target"
  sfdisk --delete "$target" 4
  sleep 2
  sync
  sleep 2
  partprobe
  sleep 2
  mkisodev 3 || exit 1
  mkwritab 5 || exit 1

 elif [ "$pt" == "msdos" ]
 then
  echo \
"- 7G
- - E
$endp
- -
quit
y" | sfdisk --append "$target"
  sleep 1
  sfdisk --delete "$target" 1 5
  sleep 2
  if $bflag
  then
   echo -e "${blueback}
Useful to boot some HP computers from around 2010:
set ${inversvid}'boot flag'$resetvid$blueback - please notice that the drive might
only boot in BIOS mode alias CSM alias legacy mode
$resetvid"
   sfdisk --activate "$target" 2
   sleep 2
  fi
  sync
  sleep 2
  partprobe
  sleep 2
  mkisodev 3 || exit 1
  mkwritab 6
  if [ $? -ne 0 ]
  then
   mkwritab 5 || exit 1
  fi
 else
  echo -e "$redback bad alsternative for partition table: '$pt' $resetvid"
  exit 1
 fi
else # not persistent
 echo \
"- -
quit
y" | sfdisk --append "$target"
 if  [ "$pt" == "msdos" ];then sfdisk --delete "$target" 1 ; fi
  sleep 2
  sync
  sleep 2
  partprobe
  sleep 2
  mkisodev 3 || exit 1
  sleep 2
  if $bflag && [ "$pt" == "msdos" ]
  then
   echo -e "${blueback}
Useful to boot some HP computers from around 2010:
set ${inversvid}'boot flag'$resetvid$blueback - please notice that the drive might
only boot in BIOS mode alias CSM alias legacy mode
$resetvid"
   sfdisk --activate "$target" 2
   sleep 2
  fi
  sync
fi
sleep 4
partprobe
sleep 2
}
########################################################################

function mkisodev {

# create ext4 file systems (and maybe remove journaling)

echo -e "$inversvid mkisodev: device=${target} partition=$1 $resetvid"

if test -b "${target}$1"
then
 echo 'y' | mkfs.ext4 -L isodevice "${target}$1"
elif test -b "${target}p$1"
then
 echo 'y' | mkfs.ext4 -L isodevice "${target}p$1"
else
 echo "could not create file system for partition $1"
 return 1
fi
}
########################################################################

function mkwritab {

# create ext4 file systems (and maybe remove journaling)

echo -e "$inversvid mkwritab: device=${target} partition=$1 $resetvid"

if test -b "${target}$1"
then
 echo 'y' | mkfs.ext4 -L writable "${target}$1"
elif test -b "${target}p$1"
then
 echo 'y' | mkfs.ext4 -L writable "${target}p$1"
else
 echo "could not create file system for partition $1"
 return 1
fi
}
########################################################################

function copyiso {

echo -e "$inversvid copying iso file to isodevice ...$resetvid"

# tweak 1: maybe modify label of partition for persistence

#echo lsblk -o label,mountpoint
#lsblk -o label,mountpoint
#echo "mntpt=$mntpt"   #######################
#echo "syslbl=$syslbl"   #######################
#read -p "press Enter to continue " ans  #######

umount "$mntpt"
sleep 2
isover=$(<<< "$syslbl" grep -o ' [0-9]*\.'|grep -o '[0-9]*')
pptarg=$(lsblk -lo name,label "$target" |grep writable|sed -e 's/ .*//' -e 's#^#/dev/#')

if [ $isover -lt 20 ]
then
 tune2fs -L casper-rw "$pptarg"
 sleep 1
fi

# tweak 2:
# To make Firefox work in Jammy & newer: 
# apparmor.service.d/30_live_mode.conf: ConditionPathExists=

if [ $isover -ge 22 ]
then
 targ1=$(mktemp -d --tmpdir dus.XXXXXXXXXX)
 /bin/echo -e "$inversvid To make Firefox work in Jammy & newer  $resetvid
 apparmor.service.d/30_live_mode.conf: ConditionPathExists="
 umount "$targ1" 2>&1
 targ0=$(mktemp -d --tmpdir dus.XXXXXXXXXX)
 mount -o loop "$source" "$targ0" 2>&1
echo '$pptarg $targ1'": $pptarg $targ1"
 mount "$pptarg" "$targ1" 2>&1
 tghme=$(find "$targ0" -name '*ubuntu*.seed')
# echo "$tghme"
 tghme=${tghme##*/}
 tghme=${tghme%.seed}
 if [ "$tghme" == "ubuntustudio" ]
 then
  tghme='ubuntu-studio'
 elif [ "$tghme" == "" ]
 then
  tghme=$(grep -om1 'ubuntu-kylin' "$targ0"/casper/filesystem.manifest)
 fi
 echo "target's home directory: /home/$tghme"
 mkdir -p "$targ1"/upper/home/"$tghme"/.config/autostart
 mkdir -p "$targ1"/upper/usr/local/sbin
 cp /usr/share/mkusb/fixfox.desktop "$targ1"/upper/home/"$tghme"/.config/autostart
 cp /usr/share/mkusb/fixfox "$targ1"/upper/usr/local/sbin
 umount "$targ1" "$targ0" 2>&1
 rm -r "$targ1" "$targ0"
# read -p "press Enter to continue"
fi

# prepare writing
size=$(stat --printf "%s\n" "$source")
mount -L isodevice "$mntpt"
sleep 0.5

# write system label
echo -e "$inversvid system label: '$syslbl' # written to 'isodevice' $resetvid
"
echo "system label: $syslbl" >"$mntpt/$syslbl"

# copy iso file with rsync
echo -e "$inversvid rsync --info=progress2 \"$source\" \"$mntpt/ubuntu.iso\" $resetvid"
rsync --info=progress2 "$source" "$mntpt/ubuntu.iso"

wf_prep
sync
umount "$mntpt"
rm -r "$mntpt"
wf_cleanup
}
########################################################################

function wf_prep {

tailfil1=$(mktemp)
if [ "$manager" == "z" ]
then
 ( watch-flush "$size" "$tailfil1" > /dev/null ) & pid00=$!

 ( tail -f "$tailfil1"| zenity --progress --title="$version - progress ..." \
 --percentage=0 --auto-close --no-cancel \
 --width=$((msiz * 500 / 100)) --height=$((msiz * 120 / 100)) \
 --window-icon="/usr/share/icons/hicolor/48x48/apps/mkusb.png"  2>> "/dev/null") & pid01=$!
 sleep 1
else
 watch-flush "$size" "$tailfil1" & pid00=$!
fi
}
########################################################################

function wf_cleanup {

echo -en "$faintvid"
if [ "$manager" != "z" ]
then
 echo ""
fi
echo "----- cleanup after writing ------------------------------------------"
sync
echo "100
# buffered data : 0 kB -- watching -- rate : 0 -- eta : n.a." >> "$tailfil1"
sleep 5.5
ps -A|grep "^ *$pid00"
if [ $? -eq 0 ]
then
 kill "$pid00"
fi
if [ "$manager" == "z" ]
then
 ps -A|grep "^ *$pid01"
 if [ $? -eq 0 ]
 then
  kill "$pid01"
 fi
fi
rm  "$tailfil1"
sleep 2
partprobe
sleep 4
umount "$target"*
echo -en "$resetvid"
}
########################################################################

function tweak_grub {

# create grub.cfg to match iso file's name

echo -e "$inversvid tweak grub ...$resetvid"

# tweak 3: search by UUID

sleep 2
partprobe
sleep 2
targ1=$(mktemp -d --tmpdir dus.XXXXXXXXXX)
uid2=$(lsblk -o uuid,label "$target" |grep -i 'usbboot'|sed "s% *usbboot%%")
uid3=$(lsblk -o uuid,label "$target" |grep 'isodevice'|sed "s% *isodevice%%")
echo "uid2=$uid2"
echo "uid3=$uid3"
mount -U "$uid2" "$targ1"
sleep 2
if [ "$uid3" != "" ]
then
 sed -i '/set isofile/'a"  search --set=root --fs-uuid $uid3" "$targ1"/boot/grub/grub.cfg
 sed -i 's/(hd0,3)/($root)/' "$targ1"/boot/grub/grub.cfg
 if [ $? -ne 0 ]
 then
  error="$error - sed: tweak 3 grub.cfg"
  result="target drive might work, but setting 'search by UUID' failed :-("
  echo "$result"
 fi
else
 error="$error - lsblk found no 'uid3': tweak 3 grub.cfg"
 result="target drive might work, but setting 'search by UUID' failed :-("
 echo "$result"
fi

# tweak 4: if layerfs in iso-file's grub.cfg

if [ "$uid3" != "" ]
then
 if $layerfs
 then
  linuxline='linux (loop)/casper/vmlinuz boot=casper layerfs-path=minimal.standard.live.squashfs iso-scan/filename=$isofile quiet splash'
  sed -i "s#linux .* persistent#$linuxline persistent#" "$targ1"/boot/grub/grub.cfg
  sed -i "s#linux .* nopersistent#$linuxline nopersistent#" "$targ1"/boot/grub/grub.cfg
  if [ $? -ne 0 ]
  then
   error="$error - sed: tweak 4 grub.cfg"
   result="target drive might work, but setting 'layerfs' failed :-("
   echo "$result"
  else
   grep 'linux.*persistent' "$targ1"/boot/grub/grub.cfg
  fi
 fi
fi
umount "$targ1"
rmdir "$targ1"
sleep 2
partprobe
sleep 1
}
########################################################################

# fixfox for versions >= 22.04 [done]

# specify how to use drive space (GiB)
#  create partition usbdata and copy backup and restore [NOT done]
#  create partition ISODEVICE (partition #4) and copy iso file to it
#   100% if 4GB drive, otherwise > 4GiB [done: now 5 GiB]
#  create partition writable and maybe copy some tweak to it [done]
#   leave 5% unallocated (to increase lifetime) [done: now 256MB]

########################################################################

function final_tasks {

# final tasks (sync, output text)

echo -e "$inversvid $syslbl $resetvid"
parted -s "$target" print
sleep 0.5
lsblk -o MODEL,NAME,FSTYPE,LABEL,MOUNTPOINT,SIZE "$target"
sync
stoptim=$(date '+%s')
usedtim=$(($stoptim - $starttim))
timestr=$(date -u --date=@$usedtim '+%H:%M:%S')
echo "Total time used [by ${version% *}] = $usedtim s; $timestr"
echo "Normal termination"
echo -e "$greenback Done :-) $resetvid"
}
########################################################################

# main

########################################################################

read_params "$@"
get_tmplt
sleep 2
sync
sleep 2
partprobe
add_parts
tweak_grub
copyiso

final_tasks
