#! /bin/bash
#
# Copyright 2014 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
# ...
# 2015-08-03  sudodus  mkusb version 9.2.3
# 2015-08-10  sudodus  added mk_grub-n-iso-s (partition 2 iso9660)
# 2015-08-10  sudodus  several fixes for the merge ...
# 2015-08-11  sudodus  generalized tests for parameters calls from main
# 2015-08-11  sudodus  parameter p for persistence
# 2015-08-12  sudodus  system files moved to '/usr/share/mkusb'
#                      grub.cfg maybe-problems.txt mkusb.cfg selected
#                      usb-pack_efi.tar.gz
# 2015-08-12  sudodus  mkusb version 10.0 'mkusb-s'
# ...
# 2016-10-16  sudodus  mkusb version 11.1.4
# ----------------------------------------------------------------------
# 2016-10-22  sudodus  created dus-persistent from mkusb
# 2016-10-23  sudodus  toram: menuentry with toram added into grub.cfg
#                      for usb-pack-efi, and menu_entry_1 edited to create
#                      it from grub.cfg of the iso file (for persistent live)
# 2016-11-20  sudodus  fix for '100% for persistence'
# 2016-11-20  sudodus  dus-persistent 0.0.1
# 2016-11-27  sudodus  made 100% for persistence more robust
# 2016-11-27  sudodus  dus-persistent 0.0.2
# 2016-12-29  sudodus  version 12.0.0 - mkusb-dus
# 2017-01-25  sudodus  improved logic when missing usb-pack-efi for distros
#                      without 'apt-get'
#                      opensuse: logic for grub2-install (in grubi386-pc)
#                      selection of usb-pack-efi when grub.cfg is missing
# 2017-01-25  sudodus  version 12.0.2
# 2017-01-31  sudodus  label=usbboot for partition #3
# 2017-01-31  sudodus  version 12.0.3
# 2017-03-29  sudodus  function menu_name when reading from block device
# 2017-03-29  sudodus  version 12.0.8
# 2017-04-30  sudodus  fixes for 17.0.4:
#                      grub-n-iso: search --set=root --fs-uuid instead of (hd0,4)
#                      select_boot_system: simpler search for "*amd64*"
# 2017-04-30  sudodus  version 12.1.1
# 2017-05-01  sudodus  grub-n-iso: search only when uuid found (not for 12.04)
# 2017-05-01  sudodus  version 12.1.2
# 2017-05-05  sudodus  ${source/.iso} --> ${source%.iso}
#                      fixes for some unusual file names
# 2017-05-05  sudodus  version 12.1.4
# 2017-05-16  sudodus  function menu_package_installer: ask to update & upgrade
#                      only installed systems (not live or persistent live)
# 2017-05-16  sudodus  version 12.1.6
# 2017-05-21  sudodus  checking for 'overlay': device name for live root clonezilla
# 2017-05-21  sudodus  version 12.1.9
# 2017-05-31  sudodus  tweaks to work with "9w-debian-wheezy"
# 2017-05-31  sudodus  version 12.2.1
# 2017-06-07  sudodus  tweaks to work with "9w-debian-jessie"
# 2017-06-07  sudodus  version 12.2.2
# 2017-06-23  sudodus  grub_n_iso: bpsiz=256 (usbboot size doubled) for debian 9
# 2017-06-23  sudodus  menu_entry_1: special treatment for debian 9
# 2017-06-23  sudodus  version 12.2.3
# 2017-08-27  sudodus  probe_source and grub_n_iso:
#                      tweaks to work with extix debian, added logical variable respin
#                      and modified evaluation of vmlinuz,initrd for debian stretch
# 2017-08-27  sudodus  version 12.2.6
# 2017-09-04  sudodus  new function partitioner: partitioning moved from grub_n_iso
#                      and 'grubimg' added to clone partitions 2 and 3 with grub for
#                      BIOS mode when running in an installed system in UEFI mode
# 2017-09-04  sudodus  version 12.2.7
# 2017-10-02  sudodus  removed redundant 'echo' output about 'grubimg'
# 2018-03-10  sudodus  zenity window sizes fixed for Ubuntu Bionic
# 2018-03-10  sudodus  version 12.3.0
# 2019-10-11  sudodus  included upefi for Debian Buster
# 2019-10-11  sudodus  version 12.3.3
# 2019-10-23  sudodus  added delays (sleep) at 'tweak 3 grub.cfg'
# 2019-10-23  sudodus  version 12.3.4
# 2019-11-09  sudodus  menu_entry_1: new menuentry with toram nopersistent
# 2019-11-09  sudodus  grub.cfg: new menuentry with toram nopersistent
# 2019-11-09  sudodus  version 12.3.7
# 2019-11-16  sudodus  modifications for nvme drives (alongside mmcblk)
# 2019-11-16  sudodus  version 12.3.8
# 2020-02-07  sudodus  parted set partition type to FAT32
#                      version 12.4.1
# 2020-03-14  sudodus  grub-n-iso: label for persistence in
#                      focal fossa 'writable'
# 2020-03-14  sudodus  version 12.4.4
# 2020-04-28  sudodus  menu_entry_1:
#                      tweaks for boot option 'maybe-ubiquity'
#                      to manage language setting
# 2020-04-28  sudodus  version 12.4.6
# 2020-04-29  sudodus  menu_entry_1:
#                      to manage 'fsck.mode=skip' to check the live system
#                      integrity in presistent live menu entries
# 2020-04-28  sudodus  version 12.4.7
# 2020-05-09  sudodus  grub-n-iso: grub-graph-prefix to improve grub menu
#                      with the grub background file mkusb-grub-bg_800x600.png
# 2020-05-09  sudodus  version 12.5.0
# 2020-05-10  sudodus  probe_source: recognizing Sparky Linux as Debian respin
# 2020-05-10  sudodus  version 12.5.1
# 2020-05-14  sudodus  grub_n_iso: removed verbosity for extraction of usb-pack_efi
# 2020-05-14  sudodus  version 12.5.2
# 2020-05-14  sudodus  separate usb-pack_efi files for grub 2.02 and grub 2.04
#                      usb-pack_efi-x.tar.gz --> usb-pack_efi-x.tar.xz
#                      for better compression
#                      Improved help text:
#                      "The image file 'grub.img.xz' is not found.
#                       - Please install the package 'usb-pack-efi' -
#                       or if it is installed, select it in the settings menu."
# 2020-05-16  sudodus  version 12.5.3
# 2020-05-23  sudodus  grub-n-iso at tweak 3: setting search by UUID failed
# 2020-05-23  sudodus  version 12.5.5
# 2020-05-27  sudodus  Silently select grub.img and usb-pack-efi, when
#                      running in an installed system in UEFI mode
# 2020-05-28  sudodus  version 12.5.6
# 2020-05-30  sudodus  find_distr, chk4uefi:
#                      recognizing Sparky Linux as host system
#                      do_n_show: added p_zentest, wf_prep, wf_cleanup
#                      to use watch-flush to show flushing buffers (sync)
# 2020-05-30  sudodus  version 12.5.7
#                      grub-n-iso: option --no-same-owner added to tar command
#                      tar -xf "$mkusb_sdir"/usb-pack_efi.tar.xz --directory "$targ1"
# 2020-09-09  sudodus  version 12.6.0
# 2020-09-12  sudodus  if grubimg, do not extract from usb-pack_efi.tar.xz
#                      use the same image as grub-2.02.img.xz and grub-2.04.img.xz
#                      (not now, maybe later simplify the logic for grubimg)
# 2020-09-12  sudodus  version 12.6.1
# 2020-09-18  sudodus  variable font and window size of zenity
#                      new function: p_zensize where msiz percent sets the size
# 2020-09-18  sudodus  version 12.6.2
# 2020-09-25  sudodus  p_zensize: added manual size for zenity font and window
# 2020-09-25  sudodus  version 12.6.4
# 2020-10-19  sudodus  probe_source: usb-pack_efi auto-set for 20.10
# 2020-10-19  sudodus  version 12.6.5
# 2021-02-03  sudodus  grub_n_iso & probe_source: identifying 20.04.2 & 21.04
#                      probe_source: usb-pack_efi auto-set for 21.04
# 2021-02-03  sudodus  version 12.6.9
# 2021-08-18  sudodus  probe_source: upefi [from now] always default for debian
# 2021-08-18  sudodus  version 12.7.1
# 2021-11-17  sudodus  quoted grep 'patterns'
# 2021-11-17  sudodus  version 12.7.2
# 2022-04-19  sudodus  apparmor.service.d/30_live_mode.conf: ConditionPathExists=
# 2022-04-19  sudodus  version 12.7.4
# 2022-05-02  sudodus  probe_source: upefi=true and grubimg=true for newer than
#                      20.04 iso files or 21.04 host systems of dus-persistent
# 2022-05-02  sudodus  version 12.7.5
# 2022-09-14  sudodus  several fixes of zenity window sizes
# 2022-09-14  sudodus  version 22.1.2
# 2023-04-21  sudodus  probe_source, grub_n_iso tweak 5: 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.1
# 2023-06-14  sudodus  partitioner:
#                      if [ "$part_type" == "gpt" ] then use template to avoid
#                      mismatch with grub versions > 2.04 (only workaround, new
#                      version of grub should be added to mkusb)
# 2023-06-14  sudodus  version 23.1.4

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

prgnam="${version% *}"
#echo "$prgnam"

mkusb_sdir="/usr/share/mkusb"
mkdir -p "$mkusb_sdir"

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'"
bs=4096
count=256
cnt=
usbonly=true
liveonly=true
startdir="$PWD"
btitle=
legacy=false

declare -a inst_prog=( "" "" )
declare param1=( \
"-h" \
"-v" \
"wipe" \
"wipe-menu" \
"wipe1" \
"wipe-1" \
"wipe-whole-device")

declare param2=( \
"all" \ 
"anh" \
"p" \
"-p" \
"persistent")
paramorig="$*"
paramnum="$#"
ctest1=
ctest2=

pvplug=
zenityplug=false
dialogplug=false
makepart=
checked_pack=false
persnote_flag=false
msdos=false
upefi=false
dni=false
niow=false
respin=false
part_type=
biosbl=
source=
srcorig=
target=
targ1=
looper=
cmdsav=
imagefile=
curlang="$LANG"
#LC_ALL=C
#LANG=C
ch_item=
distr=
disk_name_type=
release=
menuname=
ntfssize=
boundary=
endiso=
grubimg=false
pid=
tailfile=
usbdata=
percent=
size=
fontsave="$HOME/.mkusb/fontsave"  # setting for zenity window size and font
fontchar=auto
declare -i fontsize=0
msiz=
mfnt=
uver=
layerfs=false
separator="---------------------------------------------------------------------------"

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

function p_zentest {

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

function p_zensize {

fontchar=auto
fontsize=0

hpix=$(xrandr | grep -m1 ' connected'|sed -e 's/x.*//' -e 's/.* //')
#echo "hpix=$hpix"
hsiz=$(xrandr | grep ' connected'|grep -om1 ' [0-9]*mm '|grep -o '[0-9]*')
vsiz=$(xrandr | grep ' connected'|grep -om1 ' [0-9]*mm$'|grep -o '[0-9]*')
#echo "hsiz=$hsiz"
if test -s "$fontsave"
then
 read fontchar < "$fontsave"
 if [ "$fontchar" != "auto" ]
 then
  fontsize="$fontchar"
 fi
fi
if [ "$hpix" == "" ]   || [ "$hsiz" == "" ]  || [ "$vsiz" == "" ] \
|| [ "$hpix" == "0" ]  || [ "$hsiz" == "0" ] || [ "$vsiz" == "0" ] \
|| [ $fontsize -gt 0 ] && [ $fontsize -le 11 ]
then
 mf100=1100
elif [ $fontsize -gt 11 ]
then
 mf100=$((fontsize * 100))
elif [ "$vsiz" -lt "160" ]
then
 mf100=1100
elif [ "$vsiz" -lt "200" ]
then
 mf100=$((19*12*hpix/hsiz))
else
 #psiz=$((100*hsiz/hpix))
 mf100=$((19*16*hpix/hsiz))
fi
mfnt=$((mf100/100))
#echo "mfnt=$mfnt"
msiz=$((mf100/11))
}
#######################################################################
#######################################################################

function find_distr {

#distr=$(lsb_release -a 2> /dev/null|grep 'Description'|cut -f2)

distr=$(grep -i '^ID=' /etc/*release|sed s/.*ID=//) # general fix found at Fedora

#echo "$distr"
if [ "$distr" == "" ];then
 uname -a|grep -i 'ubuntu';if [ $? -eq 0 ];then distr=ubuntu;fi
 if [ "$distr" == "" ];then
  uname -a|grep -i 'debian';if [ $? -eq 0 ];then distr=debian;fi
  if [ "$distr" == "" ];then
   distr="distro_not_found"
  fi
 fi
fi
distr="${distr%% *}"
distr="${distr,,}"
echo -e "running operating system: $inversvid $distr $resetvid"
if [ "$distr" != "ubuntu" ] && [ "$distr" != "debian" ] && \
   [ "$distr" != "torios" ] && [ "$distr" != "sparky" ]
then
 mess1="Good luck :-)"
 mess2="You are trying to make a persistent live drive when running an operating
system, which is neither Debian nor Ubuntu. Maybe it will work in either
UEFI or BIOS mode, but you must probably tweak it manually."
 /bin/echo -e "$blueback
 $mess2 
$resetvid"
 if $zenityplug
 then
  warner "$mess1" "$mess2"
 else
  read -t10 -p "Press Enter to continue "
 fi
 echo -e "$inversvid Good luck :-) $resetvid"
fi
} 
#######################################################################
#######################################################################

function find_installer {

which apt-get > /dev/null 2>&1
if [ $? -eq 0 ];then
 which pv > /dev/null 2>&1
 if [ $? -ne 0 ];then
  echo "pv needs the 'universe' repository"
 fi
 inst_prog[1]="apt-get"
 inst_prog[2]="install"
else
 which yum > /dev/null 2>&1
 if [ $? -eq 0 ];then
  inst_prog[1]="yum"
  inst_prog[2]="install"
 else
  which zypper > /dev/null 2>&1
  if [ $? -eq 0 ];then
   inst_prog[1]="zypper"
   inst_prog[2]="install"
  else
   which urpmi > /dev/null 2>&1
   if [ $? -eq 0 ];then
    inst_prog[1]="urpmi"
    inst_prog[2]=""
   else
    which pacman > /dev/null 2>&1
    if [ $? -eq 0 ];then
     which pv > /dev/null 2>&1
     if [ $? -ne 0 ];then
      echo "pv needs the 'community' repository"
     fi
     inst_prog[1]="pacman"
     inst_prog[2]="-S"
    fi
   fi
  fi
 fi
fi
if [ "${inst_prog[1]}" == "" ];then
 echo " "
 echo "Cannot install $2"
 echo "None of 'apt-get' 'yum' 'zypper' 'urpmi' 'pacman' was found"
 echo "Try manually to install $2"
 echo " "
 read -t 3
fi
}

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

function menu_package_installer {

# $1 "needs" or "wants"
# $2 program name
# $3 informative test string
# $4 package name (if different from program name)

# Example (shows full syntax but smartctl is *not* used by mkusb)
# menu_package_installer wants smartctl "mkusb can work without it." smartmontools

find_installer

if [ "$4" == "" ]
then
 package="$2"
else
 package="$4"
fi
which "$2" > /dev/null
if [ "$?" != "0" ]
then
 /bin/echo -e "${version% *} $1 the program '$2': $3"
 asker "'$2': $3 Install?"
 if [ $? -eq 0 ]
 then
  if [ ${inst_prog[1]} == "apt-get" ]                             # Ubuntu and Debian
  then
   roottype="$(df | grep /$|sed 's/ .*//')"
   if [ "$roottype" != "/cow" ] && [ "$roottype" != "aufs" ] || \
      [ "$roottype" == "rootfs" ] || [ "$roottype" == "overlay" ] # installed, not live
   then
    askstr="Do you want to run 'apt-get update' and 'apt-get upgrade'?"
    echo "$askstr"
    asker "$askstr"
    if [ $? -eq 0 ]
    then
     apt-get -y update && apt-get -y upgrade
    fi
   fi
   echo "Install program $2 ... in package $package"
   echo "apt-get install --no-install-recommends $package"
   read -t 2
   apt-get install --no-install-recommends "$package"
  else
   echo "Install program $2 ... in package $package"
   echo ${inst_prog[@]} "$package"
   ${inst_prog[@]} "$package"
  fi
 fi

 which "$2" > /dev/null
 if [ "$?" != "0" ]
 then
  if [ "$1" == "needs" ]
  then
   tmpback=$redback
  else
   tmpback=$blueback
  fi
  echo -e "$tmpback $version $1 $2 but it is not installed. $resetvid"
  echo "$3"
  if [ "$1" == "needs" ]
  then
   exit
  else
   read -t 3
  fi
 fi
fi
}

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

# --colors
#    Interpret embedded "\Z" sequences in the dialog text by the following
# character, which tells dialog to set colors or video attributes:
# 0 through 7 are the ANSI used in curses:
#   0     1     2      3      4       5      6         7
# black, red, green, yellow, blue, magenta, cyan and white respectively.
#
# Bold is set by 'b', reset by 'B'.
# Reverse is set by 'r', reset by 'R'.
# Underline is #set by 'u', reset by 'U'.
# The settings are cumulative, e.g., "\Zb\Z1" makes the following text
# bold (perhaps #bright) red. Restore normal settings with "\Zn". 

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

function clean_mtab {

LANG=C

cd "$startdir"

tmp1fil=$(mktemp --tmpdir dus.XXXXXXXXXX)

grep /dev/[^f]d /etc/mtab|grep /media/|cut -d ' ' -f2|grep -v swap > "$tmp1fil"

while read tmp1str
do
 mount --fake "$tmp1str" 2>/dev/null
done < "$tmp1fil"

rm "$tmp1fil"

sync

for i in $(blkid /dev/[^f]d*|grep -v 'TYPE="swap"'|cut -d ' ' -f 1)
do mount --fake "$i" 2>/dev/null;done
#for i in /dev/[^f]d??; do mount --fake "$i" 2>/dev/null; done

for i in $(df 2>&1|grep 'No such file or directory'|sed -e 's/df: `//' -e s/\'.*//)
do
# echo umount --fake "$i"
 umount --fake "$i"
 sync
done

sed_mtab

LANG="$curlang"
echo "Cleanup after ${version% *} finished :-)"
}

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

function sed_mtab {

if [ "${inst_prog[1]}" == "urpmi" ]  # keep track of mageia's live drive
then
 return
fi

sync
for i in $(grep '^/dev/[^f]d' /etc/mtab|tr -s ' ' ' '|cut -d ' ' -f 1)
do
 match=false
 for j in $(df 2>/dev/null|grep '/dev/[^f]d'|tr -s ' ' ' '|cut -d ' ' -f 1)
 do
  if [ "$i" == "$j" ]
  then
   match=true
#   echo "$i matches"
  fi
 done
 if ! "$match"
 then
#  echo sed -i "\%^$i%D" /etc/mtab
  sed -i "\%^$i%D" /etc/mtab
 fi
done
#cat /etc/mtab

}

function prep_part_info {

sync
if [ "${1:0:11}" == "/dev/mmcblk" ]
then
 warner "Unplug and re-plug the memory card to see the correct info ..."
fi
dlay=5
echo "Wait $dlay seconds and a little more ..."
sleep $dlay
blkid -c /dev/null "$1*" > /dev/null
}
#######################################################################
#######################################################################

function partitioner {

# using parameter 2, so call with 'partitioner dummy "$2"'

# boot partition size 'bpsiz'

bpsiz=256  # the size when using 'grubimg' is set further down in this function

if test -d /sys/firmware/efi || [ "$part_type" == "gpt" ]
then
 rdev=$(df | grep -m1 '/$'|cut -d ' ' -f1)
 if ! ( [ "$rdev" == "/cow" ] || [ "$rdev" == "aufs" ] || \
    [ "$rdev" == "rootfs" ] || [ "$rdev" == "overlay" ] ) || [ "$part_type" == "gpt" ]
 then
   /bin/echo -e "$inversvid [Installed system in UEFI mode] or [GPT] then use 'grub.img' $resetvid"
   grubimg=true
   upefi=true
   part_type=gpt
   bpsiz=256  # you must modify grub.img too, when bpsiz is modified ######
   if ! test -f "$mkusb_sdir"/grub.img.xz
   then
    warner "grub.img.xz: not found" \
"The image file 'grub.img.xz' is not found.

- Please install the package 'usb-pack-efi' -

or if it is installed, select it in the settings menu."
    clear_grn "$pid" "$looper" "$targ1" "$tailfile" "$usbdata"
    exit
   fi
 fi
fi

###################
#echo -e "$redback temporary forcing 'grubimg' $resetvid"
#   grubimg=true
#   upefi=true
#   part_type=gpt
#   bpsiz=256  # you must modify grub.img too, when bpsiz is modified ######
###################

bytes=$(wc -c "$srcorig"|tail -n1|cut -d ' ' -f1)
size=$bytes

#  add {5 % for diff filesize disk-space} + 20 Mibybytes
 
mibib=$(( $bytes/1000000 + 20))

#echo "target device=${2##*/}"

targsize=$(lsblk -db /dev/[^f]d? /dev/mmcblk? /dev/nvme?n? 2>/dev/null|grep 'disk'| \
tr -s ' ' ' '|grep "${2##*/}"| cut -d ' ' -f4)
targsize=$(( ($targsize + 500000)/1000000))

#echo "targsize=$targsize"

# remove sizeof small bios_grub and boot alias efi partitions from freesize

freesize=$(( $targsize - $mibib - 2 - $bpsiz ))
if [ $freesize -lt 200 ]
then
 mess1="Too small space ( less than 200 MB )
to make a partition for persistence,

1. Install from a smaller iso file, for example Lubuntu or Debian LXDE,
2. or install to a bigger target device
3. or make a boot drive without persistence"
 echo "$mess1"
 warner "Too small space for persistence" "$mess1"
 clear_grn "$pid" "$looper" "$targ1" "$tailfile" "$usbdata"
 exit
fi

# read -p "Enter percentage of remaining space for persistence (1-100) " perc

perc=$percent

echo "$separator"
echo -e "$inversvid Selected percentage of remaining space for persistence = $perc $resetvid"
echo "$separator"
persize=$(( $perc * $freesize/100 ))
if [ $persize -lt 300 ]
then
 persize=300
 echo "First limit size of the partition for persistence is $persize MB"
elif [ $persize -gt $freesize ]
then
 persize=$freesize
 echo "Last limit size of the partition for persistence is $persize MB"
fi
echo " "
#echo "perc=$perc"

ntfssize=$(( $freesize - $persize ))

bpsiz2=$((2 + $bpsiz))
bpsiz300=$((300 + $bpsiz))
if [ $freesize -lt $bpsiz300 ] || [ $perc -eq 100 ]
then
 ntfssize=0
 persize=$freesize
elif [ $ntfssize -lt $bpsiz ]
then
 ntfssize=$bpsiz
 persize=$(( $freesize - $bpsiz ))
else
 ntfssize=$(( $freesize - $persize ))
fi
boundary=$(( $targsize - $ntfssize ))

endiso=$(( $bpsiz2 + $mibib ))
#echo "boundary=$boundary"

sync

#read -p "checking after mklabel gpt or msdos"

# creating partition table and partitions

if $grubimg
then
 upefi=true
 echo "partition 2 - bios_grub  installing via 'grub.img'"
 echo "partition 3 - fat32 boot,efi        via 'grub.img' ..."
 xzcat "$mkusb_sdir"/grub.img.xz | dd of="$2" bs=4096

 echo \
"v
x
e
r
d
w
y" \
| gdisk "$2"                 # like gpt_fix

#echo "$separator"
lsblk -f "$2" > /dev/null
#parted "$2" p
#read -p " check after flashing from grub.img.xz. Press Enter to continue"
else
 if [ "$part_type" == "gpt" ]
 then
  parted -s "$2" mklabel gpt
 else 
  parted -s "$2" mklabel msdos
 fi
 sync
 lsblk -f "$2" > /dev/null
 sleep 0.5
 
 echo "partition 1 - ntfs 'usbdata'"                              # partition 1

 if [ $ntfssize -ne 0 ]
 then
  parted -s "$2" mkpart primary ${boundary}MB 100%
 else
  boundary=$((boundary -1))
  echo parted -s "$2" mkpart primary ${boundary}MB 100%
       parted -s "$2" mkpart primary ${boundary}MB 100%
 fi
 sync
 sleep 0.5
 lsblk -f "$2" > /dev/null
 sleep 0.5
 #read -p "checking after mkpart primary ${boundary}MB 100%"

 if [ "$part_type" == "gpt" ]
 then
  echo "partition 2 - bios_grub"                        # bios-grub partition 2

  parted -s "$2" mkpart primary 1MB 2MB
  sync
  sleep 0.5
  lsblk -f "$2" > /dev/null
  sleep 0.5
 # read -p "checking after mkpart primary 1MB 2MBq"
 else
  echo "partition 2 - extended container for casper-rw"  # extended partition 2

  parted -s "$2" mkpart extended ${endiso}MB ${boundary}MB
  lsblk -f "$2" > /dev/null
  sleep 0.5
 # read -p "checking after mkpart extended ${endiso}MB ${boundary}MB"
 fi

 echo "partition 3 - fat32 boot,efi"                              # partition 3

 parted -s "$2" mkpart primary fat32 2MB ${bpsiz2}MB
 lsblk -f "$2" > /dev/null
 sleep 0.5
 #read -p "checking after mkpart primary fat32 2MB ${bpsiz2}MB"
fi

if $grubimg
then
 echo "partition 1 - ntfs 'usbdata'"                              # partition 1

 if [ $ntfssize -ne 0 ]
 then
  parted -s "$2" mkpart primary ${boundary}MB 100%
 else
  boundary=$((boundary -1))
  echo parted -s "$2" mkpart primary ${boundary}MB 100%
       parted -s "$2" mkpart primary ${boundary}MB 100%
 fi
 partprobe
lsblk -f "$2" > /dev/null ####################################################
# read -p "checking after mkpart primary ${boundary}MB 100%"
fi

echo "partition 4 - iso9660 - cloned system"                     # partition 4
parted -s "$2" mkpart primary ${bpsiz2}MB ${endiso}MB
partprobe
lsblk -f "$2" > /dev/null
sleep 0.5
#read -p "checking after mkpart primary ${bpsiz2}MB ${endiso}MB"

echo "partition 5 - ext4 - for persistence"            # partition 5
if [ "$part_type" == "gpt" ]
then
 parted -s "$2" mkpart primary ${endiso}MB ${boundary}MB
else
 parted -s "$2" mkpart logical $((endiso+1))MB ${boundary}MB
fi
partprobe
lsblk -f "$2" > /dev/null
sync
sleep 0.5
#read -p "checking after mkpart primary ${endiso}MB ${boundary}MB"

if [ "$part_type" == "gpt" ]
then
 parted -s "$2" set 1 msftdata on   # set msftdata flag on partition 1
 parted -s "$2" set 2 bios_grub on  # set bios_grub flag on partition 2
fi
parted -s "$2" set 3 boot on        # set boot flag on partition 3
sync
partprobe
lsblk -f "$2" > /dev/null
sleep 0.5
}
#######################################################################
#######################################################################

function grub_n_iso {

# parameters: <source> <target> <result>
# but let $1 be a dummy (use static $source)


#legacy=true

# mkusb_sdir=/usr/share/mkusb

LANG=C
inst=0

if [ "${2:0:11}" == "/dev/mmcblk" ] || [ "${2:0:9}" == "/dev/nvme" ]
then
 tu="${2}p"
else
 tu="$2"
fi

echo "***** tu=$tu ****************************************************"

#select_boot_system
select_partition_table
echo "selected target partition table: '$part_type'"
get_grub_pc
menu_package_installer needs gdisk "needed in order to install 'persistent live'."
menu_package_installer needs mkusb-common "needed in order to install 'persistent live'."
menu_package_installer wants usb-pack-efi "wanted in order to install 'persistent live'."

probe_source

looper=$(mktemp -d --tmpdir dus.XXXXXXXXXX)
#loopefi=$(mktemp -d --tmpdir dus.XXXXXXXXXX)
targ1=$(mktemp -d --tmpdir dus.XXXXXXXXXX)
usbdata=$(mktemp -d --tmpdir dus.XXXXXXXXXX)
tailfile=$(mktemp --tmpdir dus.XXXXXXXXXX)

# check if running an installed system in UEFI mode, and
# if 'upefi' (usb-pack_efi.tar.xz) is available

if ! $biosbl || ! test -f "$mkusb_sdir"/usb-pack_efi.tar.xz
then
 #upefi=false
# mess0="The boot system for UEFI can be fetched from the ISO file"
 echo "$separator"
# echo "$mess0"
# echo "$separator"
# warner "$mess0"
fi

# check if '/boot/grub/grub.cfg' exists in the source iso file

#echo -n "before loop mount: 'current dir'="
#pwd
mount -o loop "$srcorig" "$looper" 2>&1

select_boot_system "$looper"

if ! test -f "$looper"/boot/grub/grub.cfg && ! $upefi && ! $biosbl
then
 ng1="grub.cfg: file not found"
 ng2="In an installed system in UEFI mode,
${version% *} needs

1. either '$looper/boot/grub/grub.cfg'
   from the source iso file, but it is not found,

2. or the package 'usb-pack-efi',
   and that you select 'upefi' (and also 'grub.img'
   if you want to boot in BIOS mode),

Try a Debian Stretch or Ubuntu family *amd64* iso file."
if $zenityplug
then
 echo "$ng1"
 echo "$ng2"
fi
 umount "$looper" 2>&1
 rm -r "$looper" "$targ1" "$tailfile" "$usbdata"
 warner "$ng1" "$ng2"
 exit
elif ! test -f "$looper"/boot/grub/grub.cfg
then
 get_usb_pack_efi
fi

# general grub_n_iso progress window

( tail -f "$tailfile" |zenity --progress --title="$version - progress ..." \
--width=$((msiz * 600 / 100)) --height=$((msiz * 500 / 100)) \
--percentage=0 --auto-close --no-cancel \
--window-icon="/usr/share/icons/hicolor/48x48/apps/mkusb.png"  2>> "/dev/null") & pid=$!

echo "item 00"
echo "00
# Start grub_n_iso" > "$tailfile"

sync
sleep 1

if $upefi
then
 chk4uefi
 if [ $? -eq 1 ]
 then
  clear_grn "$pid" "$looper" "$targ1" "$tailfile" "$usbdata"
  exit
 fi
fi

# checking source file, target device and help files

#echo "$separator"
#pwd
if test -b "$srcorig"
then
 echo "'$srcorig' is identified as the source device"
elif test -f "$srcorig" && [ "${srcorig%.iso}.iso" == "$srcorig" ]
then
 echo "'$srcorig' is identified as the source ISO file"
else
 echo "'$srcorig' does not work as a source ISO file"
 exit
fi

if ! test -b "$2"
then
 echo "'$2' does not work as a target device"
 exit
fi
echo "<pre>"
lsblk -o MODEL,NAME,FSTYPE,LABEL,MOUNTPOINT,SIZE "$2"
echo "</pre>"

cd "$startdir"

echo "05
# Checking help files" >> "$tailfile"

is_file "$mkusb_sdir"/grub.cfg
if [ $? -ne 0 ]
then
 clear_grn "$pid" "$looper" "$targ1" "$tailfile" "$usbdata"
 exit
fi

source="$srcorig"

echo "item 10"
echo "10
# unmount, swapoff and wipe GPT traces and the first megabyte" >> "$tailfile"

umount "$targ1" 2> /dev/null
part="${tu}3"
#umount  "$part"
#df|grep "$part"
umount  ${tu}? 2> /dev/null
df|grep "$2"
if [ $? -eq 0 ]
then
 mess1="Cannot unmount a partition on the target device"
 echo "$mess1"
 warner "$mess1"
 clear_grn "$pid" "$looper" "$targ1" "$tailfile" "$usbdata"
 exit
fi
swapoff ${tu}? 2> /dev/null

echo "Clean for a GUID partition table"

echo "o
y
w
y"|gdisk "$2"

echo "Wipe the first megabyte (mibibyte) to get a clean boot area"

dd if=/dev/zero of="$2" bs=1024 count=1024 2>&1

# Unplug and replug the target device, if it is a memory card

prep_part_info "$2"
if [ $? -eq 1 ]
then
 clean_mtab
 exit
fi

echo "item 20"
echo "20
# make partitions: select percentage for persistence" >> "$tailfile"

partitioner dummy "$2"

#read -p "checking after all parted mkpart command lines"
#sync
#tmptxt="Un-plug and re-plug the target drive if a USB drive!"
#read -p "$tmptxt Press Enter to continue ... "
#umount ${tu}?

echo "item 30"
echo "30
# make partitions: preparing $part" >> "$tailfile"

if $grubimg
then
 /bin/echo -e "$inversvid using grub.img: keeping file system of $part: $resetvid "
else
 echo "preparing $part  ------------------------------------------------"
 dd if=/dev/zero of="$part" bs=1024 count=1024 2>&1
 sync
 umount  "$part" 2>&1
 sync
 sleep 1
 mkfs.vfat -v -F 32 "$part"
 echo " "
 sync
 sleep 0.5
fi

echo "item 40"
echo "40
# make partitions: preparing ${tu}1 and ${tu}5" >> "$tailfile"

echo "preparing ${tu}1  ------------------------------------------------"
if [ $ntfssize -gt 0 ]
then
 dd if=/dev/zero of="${tu}1" bs=1024 count=1024 2>&1
 sync
 umount  "${tu}1" 2>&1
 sync
 sleep 2
 mkfs.ntfs -v -f -L "usbdata" "${tu}1" 2>&1
 sync
 sleep 0.5
else
 echo "No space for NTFS partition ${tu}1, only placeholder"
fi
echo "preparing ${tu}5  ------------------------------------------------"
dd if=/dev/zero of="${tu}5" bs=1024 count=1024 2>&1
sync
umount  "${tu}5" 2>&1
partprobe "$2"
sync
sleep 1
mkfs.ext4 "${tu}5" 2>&1
sync
partprobe "$2"
sleep 1
#echo "<pre>"
#lsblk -f "$2"
#parted -s "$2" print
#echo "</pre>"

echo "item 50"
echo "50
# prepare for installing the system" >> "$tailfile"

mount -o loop "$srcorig" "$looper" 2>&1

tmpdir1=$(pwd)
cd "$looper"
persist=$(find * -name "vmlinuz*"|grep -e casper -e live|head -n1|cut -d '/' -f1)
vmlinuz=$(find * -name "vmlinuz*"|grep -e casper -e live|head -n1|sed 's#.*/##')
initrd=$(find * -name "initrd*"|grep -e casper -e live|head -n1|sed 's#.*/##')
cd "$startdir"

#echo "persist=$persist" ###
#echo "vmlinuz=$vmlinuz" ###
#echo "initrd=$initrd"   ###
#read -p "Enter to continue at {persist,vmlinuz,initrd}" ###

label="usbboot"
dosfslabel "$part" "$label"

if [ "$disk_name_type" == "debian" ] || [ "$disk_name_type" == "torios-debian" ]
then
 label="persistence"
else
 label="${persist}-rw"
# uver=$(grep DISKNAME "$looper/README.diskdefines"|grep buntu|tr -s ' ' '\t'|cut -f 4)
 uver=$(grep DISKNAME "$looper/README.diskdefines"|grep buntu|grep -o '[0-9][0-9]\.[0-9][0-9]')
 if [ "$uver" == "" ]
 then
  uver=$(grep -m1 -ho '[0-9][0-9]\.[0-9][0-9]' $looper/dists/*/Release 2>/dev/null|head -n1)
 fi
 if [ $? -eq 0 ]
 then
   /bin/echo -e "Ubuntu or an Ubuntu family flavour"
   echo "$uver"
   if [ "$uver" == "" ]
   then
    echo "*** Ubuntu version not found ***"
   elif test "$uver" \> "19.10"
   then
    label="writable"
   fi
 fi
fi
echo "label on partition for persistence: '$label'"
tune2fs -L "$label" -O ^has_journal "${tu}5"
partprobe "$2"

echo "$separator"
echo "source=$source"
echo "$separator"

sync
blkid -c /dev/null /dev/[^f]d?? > /dev/null

echo "item 60"
echo "60
# mount $part (the FAT partition) and check that it is mounted" >> "$tailfile"

umount "$part" 2>&1
echo "mount $part $targ1"
mount "$part" "$targ1" 2>&1
sync
df -h | grep "$part"
if [ $? -ne 0 ]
then
 /bin/echo -e "$inversvid '$part' could not be mounted $resetvid"
 umount /dev/loop* 2>&1
 warner "'$part' could not be mounted." "'$part' could not be mounted.

Poweroff and cold boot for ${version% *} to make persistent live drives again!"
 clear_grn "$pid" "$looper" "$targ1" "$tailfile" "$usbdata"
 exit
fi

echo "item 65"
echo "65
# mount ${tu}1 (the NTFS partition) and check that it is mounted" >> "$tailfile"

if [ $ntfssize -gt 0 ]
then
 umount "${tu}1" 2>&1
 mount "${tu}1" "$usbdata" 2>&1
 sync

 df -h | grep "${tu}1"
 if [ $? -ne 0 ]
 then
  /bin/echo -e "$inversvid '${tu}1' could not be mounted $resetvid"
  umount /dev/loop* 2>&1
  warner "'${tu}1' could not be mounted." "'${tu}1' could not be mounted.

Poweroff and cold boot for ${version% *} to make persistent live drives again!"
  clear_grn "$pid" "$looper" "$targ1" "$tailfile" "$usbdata"
  exit
 fi
fi

# clean if the target device is re-written without unplug and replug
# (in such cases old content may remain in the computer's memory)

if $grubimg
then
 /bin/echo -e "$inversvid use 'grub.img' so do not remove files: $resetvid "
else
 rm -r "$targ1"/* 2> /dev/null
 sync
fi

echo "item 70"
echo "70
# installing bootloaders" >> "$tailfile"

if [ "$distr" == "opensuse" ]
then
 grub_inst=grub2-install
else
 grub_inst=grub-install
fi

if $grubimg
then
 /bin/echo -ne "$inversvid UEFI Bootloader: $resetvid "
 echo "using grubimg (template image)"
else
 if $upefi
 then
  echo "upefi: usb-pack-efi"
 fi
 echo -e "$blueback $grub_inst $resetvid"
 $grub_inst --force --removable --no-floppy --boot-directory="$targ1"/boot \
 --efi-directory="$targ1"/EFI/BOOT "$2" 2>&1
fi

if $biosbl
then
 /bin/echo -ne "$inversvid UEFI Bootloader: $resetvid "
 echo -e "$blueback $grub_inst $resetvid"
 $grub_inst --force --removable --no-floppy --boot-directory="$targ1"/boot \
 --efi-directory="$targ1"/EFI/BOOT "$2" 2>&1
elif ! test -f "$looper"/boot/grub/grub.cfg
then
 if test -f "$mkusb_sdir"/usb-pack_efi.tar.xz
 then
  if ! $upefi
  then
   echo "$inversvid Select 'upefi' to use 'usb-pack-efi' $resetvid"
  fi
 else
  /bin/echo -e "$inversvid No 'grub.cfg' for the UEFI Bootloader found in the iso file $resetvid
${version% *} needs the package 'usb-pack-efi' with the file
'usb-pack_efi.tar.xz' to make a persistent live system with
this iso file boot in UEFI mode."
  if test -f /usr/bin/apt-get
  then
   echo "You can use the following command lines in a terminal window.

sudo add-apt-repository ppa:mkusb/ppa
sudo apt-get update
sudo apt-get install usb-pack-efi"
  else
   echo "
Use search string 'ubuntu dus-plus' for the tarball 'dus-plus' which contains
'usb-pack-efi'. Be prepared to tweak the system manually afterwards. It may be
difficult to create a persistent live system in your linux distro."
   echo "$separator"
  fi
 fi
 if $grubimg
 then
  /bin/echo -e "$inversvid BIOS Bootloader via 'grub.img': $resetvid "
 else
  /bin/echo -ne "$inversvid BIOS Bootloader: $resetvid "
  echo -e "$blueback $grub_inst $resetvid"
  $grub_inst --force --removable --no-floppy --boot-directory="$targ1"/boot "$2" 2>&1
 fi
fi

echo "item 80"
echo "80
# copying files ..." >> "$tailfile"

error=""

# start copy/extract boot files (not upefi) ----------------------------

if ! $upefi && test -f "$looper"/boot/grub/grub.cfg
then

# copy the boot files from the iso file

/bin/echo -e "$inversvid 64-bit bootloader: copy the boot files from the iso file $resetvid"
echo "looper=$looper"
echo "targ1=$targ1"

rsync -Ha --exclude=filesystem.squashfs "$looper/" "$targ1"
symlink_error_comment="rsync:$inversvid  don't worry, $resetvid symlink errors are *expected*
because of the target file system."
/bin/echo -e "$symlink_error_comment"
#if [ "$disk_name_type" == "debian" ] && [ "$release" == "stretch" ]
#then
# mount -o loop "$looper"/boot/grub/efi.img "$loopefi"
# rsync -Ha "$loopefi/efi" "$targ1"
# umount  "$loopefi"
# ls -l "$targ1"|grep '^d'  ###
# find "$targ1/efi"         ###
# read -p "after rsync efi" ###
#fi

is_file "$targ1"/boot/grub/grub.cfg
if [ $? -ne 0 ]
then
 echo "'$targ1/boot/grub/grub.cfg': file not found"
 echo "This way to use ${version% *} needs 'grub.cfg' from the source iso file,"
 echo "and it is available in Debian and Ubuntu family *amd64* iso files"
 clear_grn "$pid" "$looper" "$targ1" "$tailfile" "$usbdata"
 exit
fi

# tweak 1 grub.cfg

sed "$targ1"/boot/grub/grub.cfg \
-e '/menuentry/a \ set root=(hd0,4)' \
-e '/linux/s#/#($root)/#' \
-e '/initrd/s#/#($root)/#' \
> "$targ1"/boot/grub/grub.cfg0
sync
menu_entry_1 "$targ1"/boot/grub/grub.cfg0 "$targ1"/boot/grub/grub.cfg
if [ $? -ne 0 ]
then
 error="$error - menu_entry_1: tweaking grub.cfg"
fi
rm "$targ1"/boot/grub/grub.cfg0

#     tweak for  grub-graph-prefix  into  grub.cfg
#echo "tweak for  grub-graph-prefix  distr=$distr"

if [ "$distr" == "ubuntu" ]
then
 mentry1=$(grep -nm1 'menuentry' "$targ1"/boot/grub/grub.cfg|sed 's/:.*//')
 if [ "$mentry1" == "" ] || [ "$mentry1" -lt 2 ]
 then
  cat "$mkusb_sdir"/grub-graph-prefix "$targ1"/boot/grub/grub.cfg > "$targ1"/boot/grub/grub.cfg0
  if [ $? -ne 0 ]
  then
   error="$error - cat: grub-graph-prefix"
   result="failed :-("
   echo "$result"
  fi
  cp "$targ1"/boot/grub/grub.cfg0 "$targ1"/boot/grub/grub.cfg
  rm "$targ1"/boot/grub/grub.cfg0
 else
  sed -i -e '/set gfxmode=/s/^/#/' -e '/terminal_output gfxterm/s/^/#/' "$targ1"/boot/grub/grub.cfg
  mentry1=$((mentry1 - 1))
  sed -i "${mentry1}r $mkusb_sdir/grub-graph-prefix" "$targ1"/boot/grub/grub.cfg
  if [ $? -ne 0 ]
  then
   error="$error - sed: grub-graph-prefix"
   result="failed :-("
   echo "$result"
  fi
 fi
fi

###############################
#cat "$targ1"/boot/grub/grub.cfg
#clear_grn "$pid" "$looper" "$targ1" "$tailfile" "$usbdata"
#exit
###############################

else  # ... copy/extract boot files (upefi) ----------------------------

# extract files originally from Andre's zip-file (except grub.cfg grub4dos/ ini/)

#if $grubimg && diff "$mkusb_sdir"/{grub-0.img.xz,grub.img.xz} > /dev/null 2>&1
if $grubimg
then
 /bin/echo -e "$inversvid Bootloaders via 'grub.img', skipping 'usb-pack_efi': $resetvid "
 if test -f "$targ1"/boot/grub/grub.cfg
 then
  rm "$targ1"/boot/grub/grub.cfg
 fi
else
 if test -f "$mkusb_sdir"/usb-pack_efi.tar.xz
 then
  echo "using usb-pack_efi.tar.xz"
  tar --no-same-owner -xf "$mkusb_sdir"/usb-pack_efi.tar.xz --directory "$targ1"
  if [ $? -ne 0 ]
  then
   error="- tar: extracting usb-pack_efi"
  fi
 fi
fi

# tweak 2 grub.cfg

if ! test -f "$targ1"/boot/grub/grub.cfg
then
 < "$mkusb_sdir"/grub.cfg sed '2'q > "$targ1"/boot/grub/grub.cfg  # copy two first lines
 if [ $? -ne 0 ]
 then
  error="$error - sed: copying start of grub.cfg"
 fi
fi
sync
sleep 0.5
cat "$targ1"/boot/grub/grub.cfg

# append the rest of the file (after two first lines)

menu_name

< "$mkusb_sdir"/grub.cfg sed -e '1,2'd \
-e '/menuentry "ubuntu/a \ set root=(hd0,4)' \
-e '/menuentry "memtest/a \  set root=(hd0,3)' \
-e '/loopback/d' -e 's#iso-scan/filename=/ubuntu.iso ##' \
-e 's/loop/$root/' \
-e "s%ubuntu.iso%$menuname%g" \
-e "s/vmlinuz/$vmlinuz/" \
-e "s/casper/$persist/g" \
-e "s/initrd.lz/$initrd/" \
-e '/menuentry/s/"./\U&/' \
>> "$targ1"/boot/grub/grub.cfg

#read -p "at 'append the rest of the file (after two first lines)'
#disk_name_type=$disk_name_type"

if [ "$disk_name_type" == "debian" ] \
|| [ "$disk_name_type" == "torios-debian" ] \
|| [ "$disk_name_type" == "9w-debian-wheezy" ]
then
 sed -i 's/persistent --/persistence --/' "$targ1"/boot/grub/grub.cfg
fi

if [ $? -ne 0 ]
then
 error="$error - sed: appending grub.cfg"
fi

fi  # end copy/extract boot files --------------------------------------

# copy the script files 'backup' and 'restore' and the grub background file

cp "$mkusb_sdir"/backup "$targ1"
cp "$mkusb_sdir"/restore "$targ1"
cp "$mkusb_sdir"/mkusb-grub-bg_800x600.png "$targ1"
if [ $ntfssize -gt 0 ]
then
 cp "$mkusb_sdir"/backup "$usbdata"
 cp "$mkusb_sdir"/restore "$usbdata"
fi

# add files into the partition for persistence

# debian: persistence.conf

if [ "$disk_name_type" == "debian" ] \
 || [ "$disk_name_type" == "torios-debian" ] \
 || [ "$disk_name_type" == "9w-debian-wheezy" ]
then
 echo "creating persistence.conf for $disk_name_type"
 if [ "$disk_name_type" == "debian" ] && ! $niow && ! $respin
 then
  /bin/echo -e "hint: try $greenback user: 'user', password: 'live' $resetvid"
 fi
 umount "$targ1" 2>&1
 mount "${tu}5" "$targ1" 2>&1
 echo / union | tee "$targ1"/persistence.conf
fi

# change: 'Download and install automatically' to 'Display immediately'

if ! $dni
then
 /bin/echo -e \
 "$inversvid set security upgrade action to 'Display immediately' $resetvid"
 umount "$targ1" 2>&1
 mount "${tu}5" "$targ1" 2>&1
 mkdir -p "$targ1"/upper/etc/apt/apt.conf.d/
 echo 'APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Download-Upgradeable-Packages "0";
APT::Periodic::AutocleanInterval "0";
APT::Periodic::Unattended-Upgrade "0";' \
 > "$targ1"/upper/etc/apt/apt.conf.d/10periodic
 cp -p "$targ1"/upper/etc/apt/apt.conf.d/10periodic \
       "$targ1"/upper/etc/apt/apt.conf.d/20auto-upgrades
else
 /bin/echo -e "$inversvid keep current security upgrade settings $resetvid"
fi

umount "${tu}4" 2>&1
umount "${tu}5" 2>&1

# copy the iso file

which pv > /dev/null 2> /dev/null
if [ $? -eq 0 ]
then
 cmdline="< \"$srcorig\" pv -ni2 | dd of=${tu}4 bs=4096"
 if $zenityplug
 then
  do_n_show "$cmdline"
 else
  del1="$inversvid Please wait while copying and syncing"
  del2="until 'Done' is written ... $resetvid"
  echo -e "$del1 $del2"
  cmdline="${cmdline/pv -ni2/pv}"
  echo "$cmdline"
  bash -c "$cmdline"
 fi
 if [ $? -ne 0 ]
 then
  error="$error - pv and dd: cloning"
 fi
else
 echo "< $srcorig dd of=${tu}4 bs=4096"
 < "$srcorig" dd of="${tu}4" bs=4096
 if [ $? -ne 0 ]
 then
  error="$error - dd: cloning"
 fi
fi
umount "$looper" 2>&1

if [ "$error" != "" ]
then
 btext="Maybe too small partition: '$part' or '${tu}4'"
 result="failed :-("
 btitle="$version - failed :-("
 btitle="<b><span bgcolor='#ff8080'>$btitle</span></b>"
 echo "$result"
 btext="$btext
 
Error: $error"
 echo "$btext"
fi

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

if test "$uver" \> "21.10"
then
 /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 "$srcorig" "$targ0" 2>&1
 mount "${tu}5" "$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
# read -p "press Enter to continue"
fi

# tweak 3 grub.cfg

# search by UUID

sleep 2
partprobe
sleep 2
mount "$part" "$targ1" 2>&1
sleep 2
uid4="$(lsblk -Po name,uuid "${tu}4"|cut -d '"' -f 4)"
if [ "$uid4" != "" ]
then
 sed -i "s/set root=(hd0,4)/search --set=root --fs-uuid $uid4/" "$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
fi

# tweak 4 grub.cfg

# maybe-ubiquity: set language and select live or install

cmu=$(grep -c 'maybe-ubiquity' "$targ1"/boot/grub/grub.cfg)
if [ $cmu -gt 1 ]
then
 sudo sed -i '/ persistent/s/maybe-ubiquity//' "$targ1"/boot/grub/grub.cfg
 if [ $? -ne 0 ]
 then
  error="$error - sed: tweak 4 grub.cfg"
  result="failed :-("
  echo "$result"
 fi
# echo "tweak 4 test output for modified grub.cfg:" ###
# grep --color 'maybe-ubiquity' "$targ1"/boot/grub/grub.cfg ###
# read -p 'Press Enter to continue' ###
fi

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

if $layerfs
then
 sed -i "s/boot=casper/& layerfs-path=minimal.standard.live.squashfs/" "$targ1"/boot/grub/grub.cfg
 sed -i 's/maybe-ubiquity//' "$targ1"/boot/grub/grub.cfg
 if [ $? -ne 0 ]
 then
  error="$error - sed: tweak 5 grub.cfg"
  result="target drive might work, but setting 'layerfs' failed :-("
  echo "$result"
# else
#  grep 'boot=casper' "$targ1"/boot/grub/grub.cfg
 fi
fi

# umount and sync

umount "$part" 2>&1
sync
echo "Syncing the target device ..."

# final tasks

echo "item 90"
echo "90
# final tasks" >> "$tailfile"

sleep 1
tres=false
umount "$looper" "$targ1" "$usbdata" 2> /dev/null
rmdir  "$looper" "$targ1"
rm -r "$usbdata"
if [ $? -eq 0 ]
then
 tres=true
fi

# reusing 'target' to comply with original usage

target="$2"

if $tres
then
 prep_part_info "$target"
 umount ${tu}? 2> /dev/null
 echo "<pre>"
 echo "parted -s \"$2\" print"
 parted -s "$2" print
 sleep 0.5
 echo "lsblk -o MODEL,NAME,FSTYPE,LABEL,MOUNTPOINT,SIZE \"$2\""
 lsblk -o MODEL,NAME,FSTYPE,LABEL,MOUNTPOINT,SIZE "$2"
 echo "</pre>"
 if [ "$error" == "" ]
 then
  result="Done :-)"
  btitle="Work done with $target :-)"
  btitle="<b><span bgcolor='#b4df02'>$btitle</span></b>"
  echo -e "$greenback $result $resetvid"
  btext="The target device is ready to use.
'$srcorig'
was installed"
  echo "$btext"
 else
  result="Failed :-( Check carefully what happened!"
  btitle="Failed :-( Check the output to the console windows carefully!"
  echo -e "$redback $error
 $result $resetvid"
 fi  
else
 btitle="$version - failed unmounting $target :-("
 btitle="<b><span bgcolor='#ff0000'>$btitle</span></b>"
 result="Could not unmount some partition on the target device. Try manually!"
 echo -e "$redback Failed :-(
 $error 
 $result $resetvid"
fi

echo "item 100"
echo "100" >> "$tailfile"
clear_grn "$pid" "$looper" "$targ1" "$tailfile" "$usbdata"

show_result
}

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

function show_result {

LANG="$curlang"
if $zenityplug
then
 if [ "${result/:-)}" != "$result" ]
 then
  wstd=400
 else
  wstd=640
 fi
 zenity --info \
 --width=$((msiz * wstd / 100)) --height=$((msiz * 200 / 100)) \
 --title="$version - $result" \
 --text="<span font='$mfnt'><b><span bgcolor=$logorgb>$btitle</span></b>

$btext</span>" \
 --window-icon="/usr/share/icons/hicolor/48x48/apps/mkusb.png" \
 2>> /dev/null
fi
LANG=C
}
########################################################################
########################################################################

function probe_source {

looper=$(mktemp -d --tmpdir dus.XXXXXXXXXX)
#mount -o loop "${srcorig##*/}" "$looper" 2>&1
mount -o loop "$srcorig" "$looper" 2>&1

disk_name_type=

#tmpstr=$(grep 'DISKNAME' "$looper/README.diskdefines" 2>/dev/null|sed -e s/.*DISKNAME\ *//)
#if [ "$tmpstr" != "" ]
#then
# tmpst1=$(find "$looper" -iname "*release" -exec grep -m1 -o '20\.10' {} \; 2>/dev/null | head -n1)
tmpst1=$(find "$looper" -iname "*release" -exec grep -m1 -o '[0-9][0-9]\.[01][04]' {} \; 2>/dev/null | head -n1)
if [ "$tmpst1" != "" ]
then
 tmpst2=$(lsb_release -a 2>/dev/null | grep -m1 -o '[0-9][0-9]\.[01][04]'| head -n1)
 echo "target version (from iso file) $tmpst1"
 echo "host version (where dus runs)  $tmpst2"
 if [ "$tmpst1" \> "20.04" ] || [ "$tmpst2" \> "21.04" ]
 then
  upefi=true
  grubimg=true
  /bin/echo -e "$blueback version $tmpst1 boots best with grubimg and usb-pack_efi (auto-set) $resetvid"
 else
  /bin/echo -e "$inversvid iso file version $tmpst1 $resetvid"
 fi
 disk_name_type="desktop"
fi
tmpst3=$(find "$looper" -iname "grub.cfg" -exec grep -m1 -o 'layerfs-path' {} \; 2>/dev/null | head -n1)
if [ "$tmpst3" != "" ]
then
 layerfs=true
fi
echo "layerfs=$layerfs" #############

if [ "$disk_name_type" == "" ]
then
 tmpstr=$(grep -m1 'ToriOS' "$looper/isolinux/isolinux.cfg" 2>/dev/null|sed -e s/.*\ //)
 if [ "$tmpstr" != "" ]
 then
  if test -f "$looper/isolinux/ldlinux.c32"
  then
   disk_name_type="torios-debian"
  else
   disk_name_type="torios-precise"
  fi
  /bin/echo -e "$inversvid $disk_name_type $resetvid"
 fi
fi

if [ "$disk_name_type" == "" ]
then
 tmpstr=$(grep -m1 'buntu' $looper/dists/*/Release 2>/dev/null|sed -e s/.*\ //|head -n1)
 if [ "$tmpstr" != "" ]
 then
  upefi=true
  /bin/echo -e "$blueback This version boots best with usb-pack_efi (auto-set) $resetvid"
  disk_name_type="desktop"
  /bin/echo -e "$inversvid $disk_name_type $resetvid"
 fi
fi

if [ "$disk_name_type" == "" ]
then
 tmpstr=$(grep -i '9w' "$looper/isolinux/isolinux.cfg" 2>/dev/null| \
 grep -i Debian|grep -i ' 3.2'|sed 's/^.*9w/9w/')
 if [ "$tmpstr" != "" ]
 then
  niow=true
  disk_name_type="9w-debian-wheezy"
  /bin/echo -e "$inversvid $tmpstr $resetvid"
  echo ""
 fi
fi

if [ "$disk_name_type" == "" ]
then
 tmpstr=$(grep -i '9w' "$looper/isolinux/isolinux.cfg" 2>/dev/null| \
 grep -i Debian|grep -i ' 3.16'|sed 's/^.*9w/9w/')
 if [ "$tmpstr" != "" ]
 then
  niow=true
  disk_name_type="debian"
  /bin/echo -e "$inversvid $tmpstr $resetvid"
  echo ""
 fi
fi

if [ "$disk_name_type" == "" ]
then
 tmpstr=$(grep -im1 'menu label extix' "$looper/isolinux/live.cfg" 2>/dev/null)
 if [ "$tmpstr" != "" ]
 then
  respin=true
  disk_name_type="debian"
  /bin/echo -e "$inversvid $tmpstr $resetvid"
  echo ""
 fi
fi

if [ "$disk_name_type" == "" ]
then
 tmpstr=$(grep -iom1 'menu label sparky.*linux' "$looper/isolinux/isolinux.cfg" 2>/dev/null)
 if [ "$tmpstr" != "" ]
 then
  respin=true
  disk_name_type="debian"
  /bin/echo -e "$inversvid $tmpstr $resetvid"
  echo ""
 fi
fi

#echo "##### disk_name_type=$disk_name_type #####" #####################
#read -p "wait here" ans

if [ "$disk_name_type" == "" ]
then
 tmpstr=$(find "$looper" -iname "*release" -exec grep -m1 -i 'debian' {} \; 2>/dev/null |grep -m1 -i 'Debian')
 if [ "$tmpstr" != "" ]
 then
  stmp2=$(find "$looper" -iname "*release"|head -n1|sed -e 's#.*dists/##' -e 's#/.*##')
  tmpstr="$tmpstr $stmp2"
  disk_name_type="debian"
  release="$stmp2"
#  if [ "$release" == "jessie" ] || [ "$release" == "stretch" ] || [ "$release" == "buster" ] \
#     [ "$release" == "bullseye" ] 
#  then
   upefi=true
   /bin/echo -e "$blueback Debian $release boots best with usb-pack_efi (auto-set) $resetvid"
#  fi
  /bin/echo -e "$inversvid $tmpstr $resetvid"
  echo ""
 fi
fi

umount "$looper" 2>&1
rmdir "$looper"

if [ "$disk_name_type" != "desktop" ] \
&& [ "$disk_name_type" != "torios-debian" ] \
&& [ "$disk_name_type" != "torios-precise" ] \
&& [ "$disk_name_type" != "debian" ] \
&& [ "$disk_name_type" != "9w-debian-wheezy" ]
then
 mess1="Good luck :-)"
 mess2="You are trying to make a persistent live drive of an operating system,
 which is neither Debian nor Ubuntu. You must probably tweak it manually."
 /bin/echo -e "$redback
 $mess2 
$resetvid"
 if $zenityplug
 then
  warner "$mess1" "$mess2"
 else
  read -t10 -p "Press Enter to continue "
 fi
 echo -e "$inversvid Good luck :-) $resetvid"
 dni=true  # do not tamper with security updates of unknown distros
fi
}

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

function is_file {

# parameter <file-name>

if test -f "$1"
then
 echo "Using the file '$1'"
else
 mess1="'$1' not found"
 echo "$mess1"
 warner "$mess1"
 return 1
fi
}

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

function chk4uefi {

minrel=14.04
mindeb=8
minsprk=5.11

drels=$(grep 'VERSION_ID' /etc/*release|cut -d \" -f2)
distr=$(grep '^ID=' /etc/*release|cut -d = -f2)

echo "drels=$drels"
echo "distr=$distr"
 
if ! ( [ "$distr" == "ubuntu" ] && [ ${drels//.} -ge ${minrel//.} ] \
    || [ "$distr" == "debian" ] && [ ${drels//.} -ge ${mindeb//.} ] \
    || [ "$distr" == "sparky" ] && [ ${drels//.} -ge ${minsprk//.} ] )
then
 echo "$separator"
 echo "You are running the following operating system now:"
 cat /etc/lsb-release
 echo "$separator"
 mess1="Good luck :-)"
 mess2="$version

might not make all systems bootable in UEFI mode from this version.
You should work in Debian $mindeb, Ubuntu $minrel or newer
or a corresponding Ubuntu flavour (Kubuntu, Lubuntu, ... Xubuntu.)"
 /bin/echo -e "$redback
 $mess2 
$resetvid"
 if $zenityplug
 then
  warner "$mess1" "$mess2"
 else
  read -t10 -p "Press Enter to continue "
 fi
 echo -e "$inversvid Good luck :-) $resetvid"
 echo "$separator"
fi
}
########################################################################
########################################################################

function asker {

# asker <question>
if $zenityplug
then
 zenity --question --text="<span font='$mfnt'>---------- $1 ----------</span>" \
 --width=$((msiz * 760 / 100)) --height=$((msiz * 300 / 100)) \
 --title="$version - $1" \
 --window-icon="/usr/share/icons/hicolor/48x48/apps/mkusb.png" 2>/dev/null
 if [ $? -ne 0 ]
 then
  return 1
 fi
else
 ans=
 read -p "$1 (y/N) " ans
 if [ "$ans" != "y" ]
 then
  return 1
 fi
fi
}

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

function warner {

# warner <title> [message]
# message used if more than one line

if [ $# -eq 1 ]
then
 message="$1"
else
 message="$2"
fi
if $zenityplug
then
 zenity --warning --text="<span font='$mfnt'>$message</span>" \
 --width=$((msiz * 760 / 100)) --height=$((msiz * 200 / 100)) \#
 --title="$version - $1" \
 --window-icon="/usr/share/icons/hicolor/48x48/apps/mkusb.png" 2>/dev/null
else
 read -p "$message
- Press Enter to continue " ans
fi

}

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

function do_n_show {

#do_n_show <cmdline>

cmdline="$@"
cmdtext="${cmdline/ 2>&1}"
cmdtext="${cmdtext/</&lt;}"

echo "$separator"
echo "do_n_show:"
echo "$cmdtext"
echo " "
cmdfile=$(mktemp --tmpdir dus.XXXXXXXXXX)
tmpfile=$(mktemp --tmpdir dus.XXXXXXXXXX)

echo "( $cmdline && echo 'Done' > /dev/stderr ) 2>&1 \
|| ( echo '# failed';sleep 1 )"|tee $cmdfile

echo "Please wait for sync (flushing file system buffers to the device)"
echo "until 'Done' is written ..."

if [ "$manager" == "z" ] && which watch-flush
then
 wf=true
else
 wf=false
fi
if $wf
then
 wf_prep
fi

LANG="$curlang"
#bash $cmdfile |tee "$tmpfile" |sed -u 's/^100$/99/'|sed -u 's/Done/100/' | \

bash $cmdfile |tee "$tmpfile" | \
zenity --progress --title="$version - copying ..." \
 --width=$((msiz * 600 / 100)) --height=$((msiz * 200 / 100)) \
--text="<span font='$mfnt'>$cmdtext

Please wait for sync (flushing file system buffers to the device)
until 'Work done' is written ...</span>" --percentage=0 --auto-close --no-cancel \
--window-icon="/usr/share/icons/hicolor/48x48/apps/mkusb.png"  2> /dev/null
LANG=C

if $wf
then
 wf_cleanup
else
 sync
fi

ans1=$(cat "$tmpfile"|sed -e 's/</\&lt;/g' -e 's/>/\&gt;/g')
echo "'pv %'; 'dd final output'"
cat "$tmpfile"
tmpstr=$(grep 'No space left on device' "$tmpfile")
if [ $? -eq 0 ]
then
 ans1="$tmpstr"
fi
#echo "ans1=$ans1"
ans2=$(tail -n1 "$tmpfile")
rm "$cmdfile"
rm "$tmpfile"

if [ "$ans2" == "# failed" ]
then
 zenity --info --text="<span font='$mfnt'><tt>
$ans1</tt></span>" \
--title="$version - error message" \
--window-icon="/usr/share/icons/hicolor/48x48/apps/mkusb.png" 2> /dev/null
 return 1
else
 echo "do_n_show: Work done"
 echo "$separator"
fi
}
########################################################################
########################################################################

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 * 600 / 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 clear_grn {


for i in $(ps -A|grep -A4 "$1"|grep -e 'tail' -e 'zenity'|sed 's/^ *//'|cut -d ' ' -f1)
do
# echo "kill $i"
 kill $i
done
shift
umount $* 2> /dev/null
rm -rf $*

clean_mtab
}

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

function get_grub_pc {

biosbl=true
if test -d /sys/firmware/efi
then
 rdev=$(df | grep -m1 '/$'|cut -d ' ' -f1)
 if [ "$rdev" == "/cow" ] || [ "$rdev" == "aufs" ] || \
    [ "$rdev" == "rootfs" ] || [ "$rdev" == "overlay" ]
 then
  if [ "$distr" == "opensuse" ]
  then
   menu_package_installer needs grub2-install "needed in order to install 'persistent live'." grubi386-pc
  else
   menu_package_installer needs grub-install "needed in order to install 'persistent live'." grub-pc
  fi
 else
  biosbl=false
#  echo "$separator"
#  message="${version} cannot install the package 'grub-pc'
#when running in installed systems in UEFI mode. 'grub-pc' is used to make
#persistent live drives bootable in BIOS mode. So if you want a persistent
#live system, that can boot in BIOS mode, you have these alternatives:
#
#1. Boot in BIOS mode, if you can. Install and run ${version% *},
#in an installed, live or persistent live system.
#
#2. You can install 'grub-pc' in all live systems, so you can run
#${version% *} in a live or persistent live session in UEFI mode.
#
#3. You *can* also decide to use 'grubimg', the image 'grub.img.xz', later
#during this installation (in order to make a persistent live system, that
#can boot in BIOS mode)."
##  echo "$message"
##  echo "$separator"
#  warner "cannot install 'grub-pc'" "$message"
 fi
else
  if [ "$distr" == "opensuse" ]
  then
   menu_package_installer needs grub2-install "needed in order to install 'persistent live'." grubi386-pc
  else
   menu_package_installer needs grub-install "needed in order to install 'persistent live'." grub-pc
  fi
fi
}

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

function get_usb_pack_efi {

if ! test -f /usr/share/mkusb/usb-pack_efi.tar.xz \
&& ! test -f /usr/share/mkusb/grub.img.xz \
&& test -f /usr/bin/apt-get
then
 upinst=$(apt-cache policy usb-pack-efi|grep -m1 'Installed')
 if [ "${upinst/(none)}" != "$upinst" ]
 then
  menu_package_installer wants usb-pack-efi "useful in order to install 'persistent live'."
 elif [ "${upinst/Installed}" != "$upinst" ]
 then
  echo "usb-pack-efi: $upinst"
  echo "trying to reinstall usb-pack-efi ..."
  sudo apt-get install --reinstall usb-pack-efi
  echo "$separator"
 else
  echo "$separator"
  message="${version% *} will be able to create persistent live drives that work in UEFI mode
also from 32-bit iso files, if you add ppa:mkusb/ppa and install usb-pack-efi.
You can copy and paste the following three command lines to a terminal window.

sudo add-apt-repository ppa:mkusb/ppa
sudo apt-get update
sudo apt-get install usb-pack-efi"
  echo "$message"
  echo "$separator"
  warner "Install 'usb-pack-efi' manually" "$message"
 fi
fi
}

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

function menu_entry_1 {

# Usage:   menu_entry_1 <input file> <output file>
#
# Example: parser file.txt to duplicate first menuentry text including
# 
# some modifications for persistence

toram=$(mktemp --tmpdir dus.XXXXXXXXXX)
toral=$(mktemp --tmpdir dus.XXXXXXXXXX)
toubi=$(mktemp --tmpdir dus.XXXXXXXXXX)

rm -f "$2"
old_IFS=$IFS  # save the field separator           
IFS=$'\n'     # new field separator, the end of line
first=true
store=false
isubi=true
echo "set timeout=10" >> "$2"
echo "set default=0" >> "$2"

for line in $(cat "$1")
do
 if [ "${line/menuentry}" != "$line" ] && $first
 then
  if [ "${line/Lubuntu}" != "$line" ]
  then
   isubi=false
  fi
  storage="$line"
  line="${line/Try/Run}"
  line="${line/ without installing}"
  line="${line%\"*}"
  linp="${line} - persistent live\" {"
  echo "$linp" >> "$2"
  linr="${line} - set language for persistent live\" {"
  echo "$linr" >> "$toubi"
  linr="${line} - persistent live to RAM\" {"
  echo "$linr" >> "$toram"
  linr="${line} - live-only to RAM\" {"
  echo "$linr" >> "$toral"
  store=true
 elif [ "$line" == "}" ] && $store
 then
  echo "$line" >> "$2"
  echo "$line" >> "$toubi"
  echo "$line" >> "$toram"
  echo "$line" >> "$toral"
  storage="$storage
$line"
  if $isubi
  then
   cat "$toubi" >> "$2"
  else
   echo -e "Lubuntu: no 'maybe-ubiquity'"
  fi
  cat "$toram" >> "$2"
  cat "$toral" >> "$2"
  echo "$storage" >> "$2"
  store=false
  first=false
 elif $store
 then
  if [ "$disk_name_type" == "debian" ]
  then
   echo "${line}" | sed "s/linux.*/& persistence/" >> "$2"
   echo "${line}" | sed "s/linux.*/& toram persistence/"  >> "$toram"
  else
   if [ "${line/--}" != "$line" ]
   then
    echo "${line/--/fsck.mode=skip persistent --}" >> "$2"
    echo "${line/--/maybe-ubiquity persistent --}"  >> "$toubi"
    echo "${line/--/fsck.mode=skip toram persistent --}"  >> "$toram"
    echo "${line/--/fsck.mode=skip toram nopersistent --}"  >> "$toral"
   else
    echo "${line}" | sed "s/linux.*/& fsck.mode=skip persistent/" >> "$2"
    echo "${line}" | sed "s/linux.*/& maybe-ubiquity persistent/"  >> "$toubi"
    echo "${line}" | sed "s/linux.*/& fsck.mode=skip toram persistent/"  >> "$toram"
    echo "${line}" | sed "s/linux.*/& fsck.mode=skip toram nopersistent/"  >> "$toral"
   fi
  fi
  storage="$storage
$line"
 elif [ "${line/set timeout}" == "$line" ] && [ "${line/set default}" == "$line" ]
 then
  echo "$line" >> "$2"
 fi
done
IFS=$old_IFS  # restore default field separator
rm "$toubi"
rm "$toram"
rm "$toral"
}

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

function select_boot_system {

find "$looper" -name "*amd64*" > /dev/null 2> /dev/null
ans=$?

if [ $ans -eq 0 ] && test -f "$mkusb_sdir"/usb-pack_efi.tar.xz
then
 echo "select_boot_system: usb-pack_efi is available"
elif [ $ans -eq 0 ] && ! test -f "$mkusb_sdir"/usb-pack_efi.tar.xz
then
 upefi=false
 echo "select_boot_system: usb-pack_efi not available"
elif [ $ans -ne 0 ] && test -f "$mkusb_sdir"/usb-pack_efi.tar.xz
then
 upefi=true
 echo "select_boot_system: usb-pack_efi will be used"
else
 echo "select_boot_system: usb-pack_efi necessary for UEFI mode,"
 echo "please consider installing it from 'ppa:mkusb/ppa'"
fi
echo "select_boot_system: usb-pack_efi: using variable 'upefi=$upefi'"
}

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

function select_partition_table {

if $msdos
then
 part_type=msdos
else
 part_type=gpt
fi
}
########################################################################
########################################################################

function read_pff {

# reading $1
# assigning common variable(s) (declared above)

#echo "$1"
#echo "${1/pff:}"
if [ "${1:0:4}" == "pff:" ]
then
 cat "${1/pff:}"
 for i in source target percent settings
 do
  read $i
 done < "${1/pff:}"

# rm     "${1/pff:}"
# echo "settings=$settings"
 if [ "${settings/msdos}" != "$settings" ];then
  msdos=true
 fi
 if [ "${settings/upefi}" != "$settings" ];then
  upefi=true
 fi
 if [ "${settings/d-n-i}" != "$settings" ];then
  dni=true
 fi
 else
 echo "no pff input"
fi
echo "source=$source"
echo "target=$target"
echo "percent=$percent"
echo "msdos=$msdos"
echo "upefi=$upefi"
echo "dni=$dni"
}
########################################################################
########################################################################

function menu_name {

# select name of the distro for the grub menu

if test -b "$source"
then
 menuname="$(sudo blkid "$source"|grep ' LABEL='|sed -e 's/.* LABEL="//' -e 's/".*//')"
 if [ "$menuname" == "" ]
 then
  if $zenityplug
  then
   menuname=$(zenity --entry --text="<span font='$mfnt'>Enter name of the distro for the grub menu</span>" \
  --width=$((msiz * 420 / 100)) --height=$((msiz * 320 / 100)) --title="$version - Enter name" \
  --cancel-label="'linux'" --window-icon="/usr/share/icons/hicolor/48x48/apps/mkusb.png" \
  2> /dev/null)
  else
   read -p "Enter name of the distro for the grub menu " menuname
  fi
  if [ "$menuname" == "" ]
  then
   menuname=linux
  fi
 fi
else
 menuname="${source##*/}"
fi
echo "menuname: $menuname"
}

########################################################################
########################################################################
#
# dus-persistent main program
#
########################################################################
########################################################################

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

read_pff "$1"

echo "source=$source
ls -l  $source"
ls -l "$source"

if [ "$(whoami)" != "root" ] || [ "$HOME" != "/root" ]
then
 echo "Usage:"
 echo "sudo -H $0"
 exit
fi

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

srcorig="$source"

if [ "$source" == "" ] && [ "$target" == "" ]
then
 echo "No source and no target"
 exit
elif [ "$source" == "" ]
then
 echo "No source"
 exit
elif [ "$target" == "" ]
then
 echo "No target"
 exit
fi

if ! test -b "$target"
then
 echo "$target: not a block device (ex. /dev/sdx /dev/mmcblk0)"
 exit
fi

if test -s "$source"
then
 if [ "${source%.iso}.iso" == "$source" ]
 then
  echo "Making a USB boot drive or memory card .........................."
 else
  echo "Not the extension 'iso' -- try again"
  exit
 fi
elif test -b "$source"
then
 echo "Cloning a device to a USB drive or memory card ..................."
else
  echo "Bad choice -- try again"
  exit
fi

# prepare

find_distr
p_zentest
which dialog > /dev/null
if [ $? -eq 0 ]
then
 dialogplug=true
fi

# make command and run command

echo 'grub_n_iso "$source" "$target" "$result"'
echo grub_n_iso "$source" "$target" "$result"
grub_n_iso "$source" "$target" "$result"  # comment away to make it safer

sed_mtab
cd "$startdir"

clean_mtab

stoptim=$(date '+%s')
usedtim=$(($stoptim - $starttim))
timestr=$(date -u --date=@$usedtim '+%H:%M:%S')
echo "$separator
Total time used [by ${version% *}] = $usedtim s; $timestr"

