#! /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
# 2013-06-25  sudodus  linux installer from tarball of installed system
# 2013-06-27  sudodus  raring.tar.gz
# 2013-08-09  sudodus  removed lame logic for wipe as alternative to install
# 2013-09-22  sudodus  mktst selector introduced in mkusb
# 2013-09-24  sudodus  help text managed also for text screen
# 2013-09-26  sudodus  mktst selector tweaked for mkusb
# 2013-09-26  sudodus  mkusb cleaned, version 4.0
# 2013-11-17  sudodus  not only check also offer installation of pv
# 2013-11-22  sudodus  mkusb version 5.0
# 2014-01-06  sudodus  mkusb version 6.0 calls to sudo removed
# 2014-01-29  sudodus  identification of 'livedrive' fixed for live session
# 2014-01-29  sudodus  mkusb version 7.0
# 2014-01-30  sudodus  more livedrive fixes: CD, cloned iso, grub-n-iso,
#                      unetbootin, usb-creator-gtk
# 2014-01-30  sudodus  mkusb version 7.1
# 2014-03-06  sudodus  fix to recognize debian iso file and work from CD
# 2014-03-06  sudodus  mkusb version 7.2
# 2014-03-09  sudodus  second parameter 'all' to start seeing all drives
#                      usbonly=false
# 2014-03-09  sudodus  mkusb version 7.3
# 2014-03-13  sudodus  switch for help window
# 2014-03-14  sudodus  writing "Done" after installation (for xterm -hold) 
# 2014-03-14  sudodus  mkusb version 7.4
# 2014-07-15  sudodus  mkusb version 8.0-RC
# 2014-07-15  sudodus  text mode menus with dialog ...
# 2014-07-15  sudodus  function splash # removed in version 9
# 2014-07-17  sudodus  function mkhelp: help text generator separated
# 2014-07-17  sudodus  function select_device: borrowed from the OBI
# 2014-07-17  sudodus  function list_drives: improved drive recognition
# 2014-07-17  sudodus  rename mktst --> mkcmd_runcmd: existed but modified
# 2014-07-18  sudodus  mkhelp: improved help text
# 2014-07-18  sudodus  mkusb8-rc uploaded
# 2014-07-19  sudodus  outer shell and menu selection of input filemkusb1034
# 2014-07-19  sudodus  function usage_prep_final (previous main program)
# 2014-07-19  sudodus  function menu_shell
# 2014-07-19  sudodus  function special_file_select # removed in version 9
# 2014-07-19  sudodus  function general_file_select
# 2014-07-19  sudodus  function select_source
# 2014-07-21  sudodus  function check_packages
# 2014-07-21  sudodus  function mkusb_usage detached from main program
# 2014-07-21  sudodus  uncompressed image files can be used for input
# 2014-07-21  sudodus  mkusb8-rc2 uploaded
# 2014-07-25  sudodus  install cannot be selected if no input file
# 2014-07-25  sudodus  usage message mofified for version 8.0
# 2014-07-25  sudodus  mkusb version 8.0
# 2014-07-27  sudodus  list_drives bugfix: sync size with other data
# 2014-07-27  sudodus  function ch_display # removed in version 9
# 2014-07-27  sudodus  reduced focus on help text --> advanced help
# 2014-07-27  sudodus  mkusb version 8.1
# 2014-07-28  sudodus  zenity file selection menus in graphic mode
# 2014-07-29  sudodus  LANG: local language except during select_device
# 2014-07-29  sudodus  mkusb version 8.2
# 2014-07-30  sudodus  automatic selection of zenity via usage test
#                      works in text screen and terminal windows
#                      works locally and remotely via ssh -X
# 2014-07-30  sudodus  mkusb version 8.3
# 2014-08.02  sudodus  function list_drives: column count fixed with tr -s
# 2014-08-02  sudodus  mkusb version 8.4
# 2014-08-03  sudodus  function init_dialog # removed in version 9
# 2014-08-03  sudodus  function warning_dialog red bg # removed in version 9
# 2014-08-03  sudodus  function normal_dialog # removed in version 9
# 2014-08-03  sudodus  mkusb version 8.5
# 2014-08-08  sudodus  LANG=C in function mkcmd_runcmd (bugfix)
# 2014-08-08  sudodus  mkusb version 8.5.1
# 2014-08-12  sudodus  improved check if the same iso, update iso image
# 2014-08-13  sudodus  double quote the file name in the command string
#                      makes file name work with some special characters
# 2014-08-13  sudodus  function clean_mtab_n_colors_n_zerrlog syncs partitions
#                      in mtab, cleans color resource files and zenity log file
# 2014-08-13  sudodus  mkusb version 8.5.2
# 2014-08-24  sudodus  function zenitytest: usage test of zenity with icon
#                      which also serves as splash in graphics mode
#                      imgscr= mkusb24.png stored in file encoded with base64
# 2014-08-24  sudodus  function scrsizetest detached from splash
# 2014-08-24  sudodus  sudo -H mkusb recommended (due to graphics)
#                      but sudo mkusb works (and better via ssh -X)
# 2014-08-25  sudodus  function select-device's final checkpoint with zenity too
#                      arrow= arrow1.svg stored in file as svg without encoding
# 2014-08-25  sudodus  function usage_prep_final's final checkpoint with zenity too
# 2014-08-26  sudodus  cmdsav made static (declared in the head of the file)
# 2014-08-26  sudodus  function menu_package_installer
# 2014-08-26  sudodus  function mkz_msg (make zenity message)
# 2014-08-26  sudodus  mkusb.desktop using gray xterm login and xterm console
#                      window with tweaked size, colours and font
# 2014-08-27  sudodus  mkusb version 8.5.3
# 2014-08-30  sudodus  bugfix to restore red warning screen in text mode
# 2014-09-02  sudodus  fork: mkusb only GUI mode, mkusb-nox only text mode
# 2014-09-02  sudodus  dialog menus abandoned, replaced by zenity
# 2014-09-02  sudodus  blue colour abandoned to make style fit with menus by
#                      zenity --list, which are white and grey with black text
# 2014-09-06  sudodus  function help_menu
# 2014-09-06  sudodus  function use_url: BROWSER, gnome-open, xdg-open
# 2014-09-06  sudodus  mkusb version 9.0
# 2014-09-06  sudodus  wider window for Welcome and Notice about Overwriting
# 2014-09-06  sudodus  mkusb version 9.0.1
# 2014-09-07  sudodus  livedrive recognition debugged: grep -m 1 ...
# 2014-09-07  sudodus  skip if iso diskname matches on livedrive
# 2014-09-08  sudodus  zenitytest: check environment variables needed for zenity
# 2014-09-08  sudodus  fix for buggy(?) zenity --list in trusty
# 2014-09-08  sudodus  use_url: added gnome-www-browser for debian
# 2014-09-08  sudodus  added png icon for systems that cannot use svg icons
# 2014-09-08  sudodus  mkusb version 9.0.2
# 2014-09-10  sudodus  tweaked for Knoppix 7.4: adding to zenity window
#                      width and height, automatic in zenitytest
# 2014-09-10  sudodus  function tweak_zws: manual tweak of zenity window
# 2014-09-10  sudodus  function file_from_parameter for cleaner exit, so
#                      clean_mtab_n_colors_n_zerrlog called 'only' at the end
# 2014-09-10  sudodus  mkusb version 9.0.3
# 2014-09-13  sudodus  fix for Fedora: if [ "${TERM:0:5}" != "xterm" ]
# 2014-09-13  sudodus  zenity lacks the option --html in Fedora and openSUSE
# 2014-09-13  sudodus  livedrive recognition fixed for openSUSE (+ mkusb-nox)
# 2014-09-17  sudodus  function find_distr: better way to identify distro
# 2014-09-17  sudodus  function final_checkpoint_legacy: used when no --html
# 2014-09-17  sudodus  function mkz_html: used when -html works
# 2014-09-17  sudodus  function mkz_legacy: used when no --html
# 2014-09-17  sudodus  function zenitylegacy: checks zenity with no --html
# 2014-09-18  sudodus  livedrive recognition for knoppix
# 2014-09-18  sudodus  find_installer: finds and selects apt-get yum zypper urpmi
# 2014-09-18  sudodus  tweaks for opensuse (desktop file, manual browsing)
# 2014-09-18  sudodus  mkusb version 9.0.4
# 2014-09-25  sudodus  when identifying if iso testing: try to unmount partitions
#                      except swap partitions, and consider drives with an active
#                      swap partition busy, 'variable bizz'
# 2014-09-25  sudodus  function same_iso: separated from usage_prep_final
# 2014-09-26  sudodus  function sed_mtab: clean mtab
# 2014-09-26  sudodus  mkusb version 9.0.5
# 2014-09-28  sudodus  exception for mageia in sed_mtab
# 2014-09-28  sudodus  opensuse works with zenity -html (bug-fix in zenity)
# 2014-09-29  sudodus  mkusb version 9.0.6
# 2014-09-30  sudodus  livedrive recognition for installed fedora 
# 2014-09-30  sudodus  mkusb version 9.0.7
# 2014-10-02  sudodus  added zenity window width and height for debian jessie
# 2014-10-02  sudodus  modprobe loop  # for debian jessie
# 2014-10-08  sudodus  echoing "pv needs ..." only when pv is not installed
# 2014-10-08  sudodus  improved text in "Select device - notice and overview" 
# 2014-10-08  sudodus  mkusb version 9.0.8
# 2014-10-08  sudodus  zenity --list "Action for ${imagefile##*/}" fix for Trusty
#                      because the slashes of a full path not accepted after return
# 2014-10-15  sudodus  function work_flow describes the sequence of zenity windows
# 2014-10-15  sudodus  and the corresponding manual file is updated
# 2014-10-15  sudodus  notice and overview - "Select drive in the next window"
# 2014-10-16  sudodus  mkusb version 9.1
# 2014-10-22  sudodus  zenity --window-icon="/usr/share/icons/mkusb.png"
#                      used in --list windows in 3.12.1
# 2014-10-22  sudodus  mkusb version 9.1.1
# 2014-11-19  sudodus  "Please wait for sync (flushing file system buffers
#                      to the device) until 'Done' is written ..."
# 2014-11-19  sudodus  mkusb version 9.1.2
# 2014-11-22  sudodus  cd to source file directory to keep partition mounted
# 2014-11-22  sudodus  mkusb version 9.1.3
# 2014-12-07  sudodus  final text for wipe-whole-device improved
# 2014-12-07  sudodus  mkusb version 9.1.4
# 2015-04-03  sudodus  current directory changed to that of the source file, so
#                      source=${source##*/} ... to manage path in parameter
# 2015-04-03  sudodus  clone a device (typically a CD drive or USB drive)
# 2015-04-03  sudodus  mkusb version 9.1.5
# 2015-05-17  sudodus  icons located according to standards.freedesktop.org
# 2015-05-19  sudodus  zenity --window-icon="/usr/share/icons/hicolor/48x48/apps/mkusb.png"
#                      used in --list windows in 3.12.1
# 2015-05-17  sudodus  mkusb version 9.1.6
# 2015-06-21  sudodus  tries to unmount only usb drives when usbonly
#                      and does not try to unmount drives in fstab
# 2015-06-21  sudodus  mkusb version 9.2
# 2015-06-22  sudodus  removed 2 lines (<img class ...) from arrow=
# 2015-06-22  sudodus  livedrive=$(df |grep /$|cut -c 5-8)
# 2015-06-22  sudodus  mkusb version 9.2.1
# 2015-08-01  sudodus  hadd, wadd changed for debian jessie
# 2015-08-01  sudodus  made gentler warning texts (to avoid scaring new users)
# 2015-08-01  sudodus  licence text in about
# 2015-08-01  sudodus  changed background for the final checkpoint window
# 2015-08-01  sudodus  function coledit for inline editing of background colours
# 2015-08-01  sudodus  function colsel called by coledit
# 2015-08-02  sudodus  mkusb version 9.2.2
# 2015-08-03  sudodus  background colours saved in /root/.mkusb
# 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-10  sudodus  mkusb wants wmctrl
# 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'
# 2015-08-12  sudodus  minor tweaks
# 2015-08-12  sudodus  mkusb version 10.0.1
# 2015-08-13  sudodus  minor tweak to help text
# 2015-08-13  sudodus  in grub_n_iso: btitle="$version - Work done with $2 :-)"
# 2015-08-14  sudodus  more bug-fixes and improvements of the output to the user
# 2015-08-17  sudodus  A screllbar is added to the mkusb console window.
# 2015-08-17  sudodus  checking for sudo -H and password via a zenity window
# 2015-08-17  sudodus  mkusb starts in the user's home directory
# 2015-08-17  sudodus  function probe_source
# 2015-08-17  sudodus  mkhelp: lsblk -o NAME,MODEL,FSTYPE,LABEL,MOUNTPOINT,SIZE,NAME
# 2015-08-17  sudodus  mkusb version 10.0.2
# 2015-08-20  sudodus  mkusb-st2: zenity 2> /dev/null
# 2015-08-21  sudodus  mkusb-st2: smooth login in live sessions
# 2015-08-21  sudodus  mkusb version 10.0.3
# 2015-08-31  sudodus  grub_n_iso: target --> targ1 to avoid confusion in live systems
# 2015-08-31  sudodus  sync after creating partitions (in 'grub_n_iso')
# 2015-08-31  sudodus  clean the target's partitions because old content may survive
#                      wipe first megabyte of boot and casper-rw partitions
# 2015-09-01  sudodus  mkusb needs grub-pc to install 'persistent live'
# 2015-09-01  sudodus  mkusb version 10.0.4
# 2015-09-03  sudodus  grub_n_iso: sync,sleep,lsblk,blkid,df commands added
# 2015-09-03  sudodus  to make the FAT partition mount and check it in 15.04
# 2015-09-03  sudodus  blkid --> blkid /dev/[^f]d?? to avoid delay because of floppy
# 2015-09-03  sudodus  lsblk --> lsblk /dev/[^f]d? to avoid delay because of floppy
# 2015-09-03  sudodus  mkusb version 10.0.5
# 2015-09-03  sudodus  menu_shell: Persistent live selected
# 2015-09-05  sudodus  mkusb version 10.0.6
# 2015-09-05  sudodus  function asker: replaces read -p with zenity
# 2015-09-05  sudodus  function warner: replaces read -p with zenity
# 2015-09-05  sudodus  function do_n_show: replaces pv with zenity --progress
# 2015-09-05  sudodus  function clear_grn: unmount and remove temp files/dirs of grub_n_iso
# 2015-09-05  sudodus  function dnward_win: position for general progress window (0,10,100)
# 2015-09-07  sudodus  various tweaks to make independent of the console
# 2015-09-07  sudodus  viewing the ~/mkusb.log at the end of mkusb-start
# 2015-09-07  sudodus  mkusb version 10.1
# 2015-09-09  sudodus  several tweaks for parsing ~/mkusb.log (user interface)
# 2015-09-09  sudodus  mkusb version 10.1.1
# 2015-09-14  sudodus  function wipe_menu: more wiping choices
#                      wipe-1, wipe-whole-device,
#                      wipe-1 and make mkusb partition table + fat32 file system
#                      wipe-1 and make guid partition table
# 2015-09-14  sudodus  function mk_msdos
# 2015-09-14  sudodus  function mk_gpt_skel
# 2015-09-15  sudodus  function mk_gpt_ntfs
# 2015-09-15  sudodus  function mk_gpart
# 2015-09-15  sudodus  function part_info
# 2015-09-15  sudodus  mkusb version 10.2
# 2015-09-30  sudodus  grub.cfg template file modified (memory test entry)
# 2015-09-30  sudodus  grub_n_iso: memtest entry in grub menu modified
# 2015-09-30  sudodus  mkusb version 10.2.1
# 2015-10-01  sudodus  mk_gpart; typing error 2 GB --> 2 TB 'big drive'
# 2015-10-01  sudodus  menu_shell: dl_img removed (old cruft)
# 2015-10-01  sudodus  mkusb version 10.2.2
# 2015-10-07  sudodus  creating GPT with NTFS windata partition for persistent system
# 2015-10-07  sudodus  mkusb wants gdisk
# 2015-10-07  sudodus  mkusb version 10.3
# 2015-11-12  sudodus  polishing zenity window texts
# 2015-11-12  sudodus  mkusb version 10.3.1
# 2015-11-14  sudodus  fixed bug for 100% persistence: zero size placeholder
#                      as partition #1, normally the usbdata partition with NTFS
# 2015-11-14  sudodus  mkusb version 10.3.2
# 2015-11-16  sudodus  fixed bug when too small space ( < 200 MB ) for persistence
# 2015-11-16  sudodus  fixed bug with pid confusion (pid at percentage ---> pidf)
# 2015-11-16  sudodus  mkusb version 10.3.3
# 2015-11-24  sudodus  grub_n_iso: add scripts for backup and restore
# 2015-11-24  sudodus  mkusb version 10.3.4
# 2015-11-26  sudodus  function get_grub_pc
# 2015-11-26  sudodus  mkusb version 10.3.5
# 2015-11-27  sudodus  modified method to make persistent live drives
#                      using either data from the source iso file
#                      or data from usb-pack_efi.tar.gz to boot
#                      function menuentry_1
#                      function select_boot_system
# 2015-11-27  sudodus  mkusb version 10.4
# 2015-11-30  sudodus  scrorig --> srclocal in 'mount -o loop "$srclocal" "$looper"'
# 2015-11-30  sudodus  mkusb version 10.4.1
# 2015-12-03  sudodus  grep -m1 in calculation of infstb (drive in fstab and busy)
# 2015-12-03  sudodus  mkusb version 10.4.2
# 2015-12-13  sudodus  made possible the select any file-name '*' for the source file
#                      'Tip: There should be an extension, and the extension should
#                      be written with lower-case letters ...'
# 2015-12-13  sudodus  another LANG="$curlang" when exiting from select-device
# 2015-12-13  sudodus  mkusb version 10.4.3
# 2015-12-14  sudodus  mkusb can select block device as input via the menu
#                      if test -f "$imagefile" || test -b "$imagefile"
#       sr? and sd? in --file-filter={*.i[sm][og]*,*.iso,*.img,*.img.?z,s[dr]?,*}
# 2015-12-14  sudodus  mkusb version 10.4.4
# 2015-12-15  sudodus  minor bug-fix: cleaning when quitting from get_percent
# 2015-12-15  sudodus  mkusb version 10.4.5
# 2016-01-06  sudodus  when bad password mkusb-start changes title bar
#                      'mkusb - password' --> 'password: try again!'
# 2016-01-06  sudodus  mkusb version 10.4.6
# 2016-01-14  sudodus  persistence for debian: boot option, label, config file 
# 2016-01-14  sudodus  mkusb version 10.5
# 2016-02-06  sudodus  persistence for torios-debian
# 2016-02-06  sudodus  mkusb version 10.5.1
# 2016-03-28  sudodus  function select_partition_table (gpt or msdos)
# 2016-03-28  sudodus  mkusb version 10.6
# 2016-03-31  sudodus  fixes for Xubuntu 16.04 LTS (mounting and unmounting)
# 2016-03-31  sudodus  mkusb version 10.6.1
# 2016-04-11  sudodus  xz --robot --list
# 2016-04-11  sudodus  mkusb version 10.6.2
# 2016-04-13  sudodus  removed double wiping (skipped in mk_msdos)
# 2016-04-13  sudodus  mkusb version 10.6.3
# 2016-05-20  sudodus  fix to allow spaces and special characters in path
# 2016-05-20  sudodus  function gpt_fix
# 2016-05-20  sudodus  mkusb version 10.6.4
# 2016-05-24  sudodus  function gpt_zap
# 2016-05-24  sudodus  mkusb version 10.6.5
# 2016-05-24  sudodus  improved logic to invoke gpt_fix
# 2016-05-24  sudodus  mkusb version 10.6.6
# 2016-07-21  sudodus  enabled alternative without usb-pack_efi.tar.gz
#                      advantage: free software
#                      disadvantage: 32-bit version do not boot in UEFI mode
# 2016-07-21  sudodus  mkusb version 11.0.0
# 2016-07-26  sudodus  function get_usb_pack_efi
# 2016-07-26  sudodus  mkusb version 11.0.1
# 2016-09-03  sudodus  function chk4ubuntu_upgrades
#                      change 'Download and install automatically'
#                      to 'Display immediately'
# 2016-09-03  sudodus  mkusb version 11.0.2
# 2016-09-14  sudodus  fix to manage flash cards seen as /dev/mmcblk0
# 2016-09-14  sudodus  mkusb-nox version 11.0.3
# 2016-09-17  sudodus  function select_source_as_user replaces
#                      select_source and general_file_select
#                      runs 'as user' not 'as root', mmcblk? added to filter
# 2016-09-17  sudodus  mkusb version 11.0.{4,5}
# 2016-09-19  sudodus  check for $(whoami) instead of $USER for fedora 24
# 2016-09-19  sudodus  mkusb version 11.0.6
# 2016-09-20  sudodus  fixes for opensuse 42.1:
#                      disk/by-id/ 'scsi' accepted because 'usb' not used
#                      select file as root because regular user fails
# 2016-09-20  sudodus  mkusb version 11.0.7
# 2016-09-20  sudodus  default isdisplay=0 (alias default 'OK')
# 2016-09-20  sudodus  mkusb version 11.0.8
# 2016-10-06  sudodus  mkusb 'needs rsync' (not default in debian sid)
#                      (only mkusb-nox, making boot drives with Windows
#                      debian: replaced rsync (not default) with cp and
#                      removed 'insmod' lines with grep -v for grub.cfg)
#                      put debian 'on par' with ubuntu in text strings
#                      and some logical expressions to activate pop up
#                      windows with (messages and warnings)
# 2016-10-06  sudodus  mkusb version 11.1.1
# 2016-10-07  sudodus  tweaked window sizes to display the whole title
# 2016-10-06  sudodus  persist_check_body_bg: separate background colour
#                      of the final checkpoint when persistent live
#                      fix for new format of the colour specification
#                      fix for text mode browser (run in xterm) 
# 2016-10-07  sudodus  mkusb version 11.1.{2,3}
# 2016-10-16  sudodus  bugfix in chk4uefi: check of version numbers
# 2016-10-16  sudodus  mkusb version 11.1.4
# 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-10-23  sudodus  mkusb version 11.1.5
# 2016-11-11  sudodus  minor bug-fix (zenity window size)
# 2016-11-11  sudodus  mkusb version 11.1.6
# 2016-11-20  sudodus  fixed bug for 100% persistence: using ntfssize
# 2016-11-20  sudodus  mkusb version 11.1.7
# 2016-11-26  sudodus  colour selection: different text for each case: use $1
# 2016-11-26  sudodus  mkusb version 11.1.8
# 2016-11-29  sudodus  reset alternate usage of 'cancel' button because it
#                      caused confusion when the x button is used
# 2016-11-29  sudodus  mkusb version 11.1.9
# 2016-12-28  sudodus  version mkusb-11; dus is the main version
#                      minor bugfix: commented away echo to "toram"
# 2016-12-28  sudodus  mkusb version 11.2.0
# 2017-02-11  sudodus  mkusb.desktop: added %f and mkusb-start: "$@"
#                      to transfer source file as parameter and via 'selected'
# 2017-02-11  sudodus  mkusb version 11.2.1
# 2018-03-10  sudodus  zenity window sizes fixed for Ubuntu Bionic
# 2018-03-10  sudodus  version 11.2.2

version="mkusb 11.2.2"

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

mkusb_sdir="/usr/share/mkusb"
mkdir -p "$mkusb_sdir"
hlptxt="/tmp/help-mkusb.txt"
selected="$mkusb_sdir"/selected
tgfile="$mkusb_sdir"/mkusb.cfg
tgfil0="/root/.mkusb"
if test -f "$tgfil0"
then
 asker "Do you want to import mkusb settings from '$tgfil0'? "
 if [ $? -eq 0 ]
 then
  mv "$tgfil0" "$tgfile"
 fi
fi

# Original red background
#<body style='background:#cc0000;'>
# Orange background
#<body style='background:#e8a020;'>
# Blue background
#<body style='background:#2252a0;'>
# Light blue background
#<body style='background:#3580ca;'>
# Green-yellow final text background and login colour
#<body style='background:#b4df02;'>
# Console window grey
#<body style='background:#ebeceb:'>

final_check_body_bg='#dd0000'
persist_check_body_bg='#e8a020'
iso_test_body_bg='#3580ca'
if test -s "$tgfile"
then
 while read -r tmpc
 do
  if [ "${tmpc%=*}" == "final_check_body_bg" ]
  then
   final_check_body_bg="${tmpc#*=}"
  elif [ "${tmpc%=*}" == "persist_check_body_bg" ]
  then
   persist_check_body_bg="${tmpc#*=}"
  elif [ "${tmpc%=*}" == "iso_test_body_bg" ]
  then
   iso_test_body_bg="${tmpc#*=}"
  fi

 done < "$tgfile"
fi
inversvid="\0033[1;7m"
resetvid="\0033[0m"

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="$#"
system=
ctest1=
ctest2=
icenter=

pvplug=
zenityplug=
makepart=
splashed=false
checked_pack=false
persnote_flag=false
upefi=true
part_type=
biosbl=
source=
srcorig=
system=
systag=
spec_src=
target=
looper=
cmdsav=
imagefile=
curlang="$LANG"
LC_ALL=C
#LANG=C
width=
ch_item=
wadd=0
hadd=0
distr=
disk_name_type=
chk_upgrd=false
zerrlog=
separator="---------------------------------------------------------------------------"
imgsrc="\
<img class='inline-image' src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB
gAAAAYCAYAAADgdz34AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAN1wAADdcBQiibeAAAABl0RVh0U
29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAUvSURBVEiJlZVtjF1VFYaftfc5p/Nxb+fjlmZG
2oZM2tEGJcZOY9IBhNiKQeMUDGgT2jghUhoU/2jQNnzVQgIJxB9CrCQlTOsPQEMmBQItTaxhJtoh6hR
pbVpbtU6ndDqXGTsz995zzt6LH+fe6eVjGl3JSs45++z33Xut9a4lqsoVzAC9zs/cpWgfos5rMiWqk4
qZiGzrQTDPA5WFAGQBgs7EXXrUGHNHOR235+ZeaJqYG7QinsgWCE2B0LTT0bR5ZnHUk4hEOw3hbqD0v
xCsdn728JlLz7WdvbQ7iP1JrAFrBCtgRECyH1WhOfgS1+R/PtcSrkutadgCdvBKBNc7Lb3+1wvbcuNz
eyW0QmCEwEJQIzBSw8er4hWch1ywji8UXitZaf4a8HZ9jKvm+lI/e2D43O35sdm9Yo1gDQQWQiOEVgg
DIbIQBXLZrZCU4A+HhzhWvLPRa+l1YPXHCRpTXx44/J+vN14svYkVMnCT3eDEKNx9S8JtPQkn34XICj
4W9jzl+f43UzZ0Jwz8wjGdHOTE1H05p7OHgc55Ak+ydaI0FBTLQxgRzHy8M6Inf5Lytz8rZ88or73ki
AJhcR7+flT5yx89LoU16wzWwIXyXhmbea7N+UuP1ggWeR8/NHphR5MAIjUXjAhjZ+Ds6ct58mkWplf2
eg696ua/r+kVTLUIxmZ/HSDmDsAE4PuL5ZGwWH6HRUGWwJp7Bz/tT5mdgc+sEG78quVH20P2v+R4YFu
MKtz6bUtPr+G6tQYRRVBK7iTldNw2hyt7TeymNpyeHsh9QgkCw295Th1TghB2/zbisWdCRoY9938vxn
tY/w3L03tClncJW/sSpoqXt5+be6HJ+Zm7jOKvit3kfF0rVVd4dyQLzYY+Q9fn4MB+xw+3VHAOblxve
eY3EUfe9vxgU8zREc+2byUUJ7K952cHraJ9BpVCJa0S1Eiqbmx2GhvA79/w3L85Jk3gyzcYnn0xgkB5
YkdKparff/1DOXHUoyiqDo9zgTVha6V6A6914lFYenW2cfiQcuCVhCTO3oMIdj0QM3rEc/xodktj4cF
fWnpuFpJUCcICeDcVgFgRU6dMwXmwAq1LMs0WJz7aToYO+fnnMIL7HrRcu0ZY9UVInOIUrLSjopOBII
PL8hvvnq4cs1qVvRElFTh17DJo+1L4zj2WpR3C+2PKxfeVJR3C+o1Cxwoh9UrqIPWQeiUwBQQzEViT2
9fV0r/pvYuP5wGcV4wI5/8N+weyk678vPDkPkthaVbnIjJfFF6V2CnOawbuFOeUFfnNM5FtPWiAocag
0+Wj7vlEn3pP+dmdng8m4JrPwq4BQ3O7kjiInRKnVXeZJy5bS52SeiUX9dC2aG0C5nmThd6/vKrt3hT
g+Ajs3ALTk7CiGx4ZEBpblKQGWAecEUGcZiRxlejawq45Y6KdQKXWrjtTPzv67Isbl/y4/y1JKrC8G7
bvgfYlWVettYG6cTBf1l6zxDoP7Q293Lz8jf8GprkDKNXPg9Vj42eOXH/TdTnHDNv3wOL2qqiljqCq8
hqD1qrPQ0fzLdyw7HelwDRsqg2eTwycc+f/eXB4/LsNccOf+H+sq2WLru381YyVxlupGzifMjJdX+rL
AxOloWD0wo6mYvmdKwLno25Wtd2brmy954PANH8FOF6/vtDQb/QkW72PHyqWR8LT0wO52E1SSSepuEl
EDMvyG11XS/9cY9DpVP3Loc0/DIx/HGghgpotAt8fu6kNir8KlYKIbTVirSCD1uT2AUOAXwjgQ+w2nU
d1pQGqAAAAAElFTkSuQmCC' alt='mkusb24.png' />"

arrow='

<svg
   xmlns:dc="http://purl.org/dc/elements/1.1/"
   xmlns:cc="http://creativecommons.org/ns#"
   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
   xmlns:svg="http://www.w3.org/2000/svg"
   xmlns="http://www.w3.org/2000/svg"
   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
   width="32"
   height="64"
   id="svg2985"
   version="1.1"
   inkscape:version="0.48.3.1 r9886"
   sodipodi:docname="Nytt dokument 2">
  <defs
     id="defs2987">
    <marker
       inkscape:stockid="Arrow2Mend"
       orient="auto"
       refY="0"
       refX="0"
       id="Arrow2Mend"
       style="overflow:visible">
      <path
         id="path3794"
         style="fill-rule:evenodd;stroke-width:0.625;stroke-linejoin:round"
         d="M 8.7185878,4.0337352 -2.2072895,0.01601326 8.7185884,-4.0017078 c -1.7454984,2.3720609 -1.7354408,5.6174519 -6e-7,8.035443 z"
         transform="scale(-0.6,-0.6)"
         inkscape:connector-curvature="0" />
    </marker>
  </defs>
  <sodipodi:namedview
     id="base"
     pagecolor="#ffffff"
     bordercolor="#666666"
     borderopacity="1.0"
     inkscape:pageopacity="0.0"
     inkscape:pageshadow="2"
     inkscape:zoom="2"
     inkscape:cx="19.840889"
     inkscape:cy="24.891926"
     inkscape:current-layer="layer1"
     showgrid="true"
     inkscape:document-units="px"
     inkscape:grid-bbox="true"
     inkscape:window-width="744"
     inkscape:window-height="759"
     inkscape:window-x="472"
     inkscape:window-y="93"
     inkscape:window-maximized="0" />
  <metadata
     id="metadata2990">
    <rdf:RDF>
      <cc:Work
         rdf:about="">
        <dc:format>image/svg+xml</dc:format>
        <dc:type
           rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
        <dc:title></dc:title>
      </cc:Work>
    </rdf:RDF>
  </metadata>
  <g
     id="layer1"
     inkscape:label="Layer 1"
     inkscape:groupmode="layer">
    <path
       style="fill:none;stroke:#000000;stroke-width:3;stroke-linecap:butt; \
        stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1; \
        stroke-dasharray:none;marker-end:url(#Arrow2Mend)"
       d="M 28.933437,2.2938363 C 12.729668,18.171797 9.6147411,38.412704 9.2483809,59.569801"
       id="path4393"
       inkscape:connector-curvature="0"
       sodipodi:nodetypes="cc" />
  </g>
</svg>'

# arrow="arrow1.svg"

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

function zenitytest {

LANG=C

htmlbody="<html>
<!-- <body style='background:#b4df02'> -->
<body style='background:#ebeceb'>
$imgsrc
<span style='font-family:arial;font-size:18px;'>
<sup>- $version</sup>
</span>
</body>
</html>"

echo "TERM=${TERM}"

#if [ "${TERM:0:5}" != "xterm" ]     # fix for Fedora
if [ "${TERM:0:5}" == "linux" ]     # fix for mkusb version 10.1
then
 echo " "
 echo "no X:  $version  needs a graphical desktop environment or window manager"
 echo "try    mkusb-nox  which runs in text screens 'with no X'"
 echo " "
 echo "sudo mkusb-nox <input-file>"
 echo " "
 exit
elif [ "$DISPLAY" == "" ]
then
 echo " "
 echo "The environment variable DISPLAY is blank. If you run a server via ssh,"
 echo "try mkusb-nox which runs in text screens 'with no X'"
 echo " "
 echo "sudo mkusb-nox <input-file>"
 echo " "
 exit
fi

# tweaks for distros where the default window size does not work

find_distr

if [ "$distr" == "opensuse" ]
then
 hadd=60
 wadd=0
#elif [ "$distr" == "debian" ]  # jessie may need this (default OK for wheezy)
#then
# hadd=50
# wadd=50
fi

ls / | grep KNOPPIX
if [ $? -eq 0 ]
then
 hadd=120
 wadd=100
fi

# end tweaks

errout=$(mktemp)
zerrlog=$(mktemp)
touch "$zerrlog"
chmod ugo+rwx "$zerrlog"

(echo "$htmlbody") | zenity --text-info --html --filename=/dev/stdin \
--height=$(($hadd+120)) --title "" --timeout 1 2>> "$errout"

exitnr=$?
grep 'The owner of' "$errout"
sudoH=$?
if [ $sudoH -eq 0 ]
then
 echo "#####  Use  sudo -H mkusb  #####"
fi

if [ $exitnr -eq 0 ] || [ $exitnr -eq 5 ]
then
 zenityplug=true
elif [ $exitnr -eq 1 ]
then
 if test -s "$errout"
 then
  if [ $sudoH -ne 0 ]
  then
   zenityplug=false
  fi
 fi
else
 zenityplug=false
fi

if $zenityplug
then
 splashed=true
# echo "zenity"
else
 echo " "
 echo "zenity does not work"
 echo " "
# echo "exitnr=$exitnr"
 cat "$errout"

 if [ "$distr" == "fedora" ]
 then
  echo " "
  echo "In Fedora 20, Zenity lacks the option --html,"
  echo "which is used in many dialogue windows by mkusb 9. Until that"
  echo "is fixed, only a colourless legacy version of mkusb works."
  echo " "
#  read -t 3
 fi
fi

LANG="$curlang"
rm "$errout"
}

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

function coledit {

newcol=
rm "$tgfile"

zenity --question --text="Reset the background colours?"
if [ $? -eq 0 ]
then
 final_check_body_bg='#dd0000'
 persist_check_body_bg='#e8a020'
 iso_test_body_bg='#3580ca'
fi
colsel "final_check_body_bg" "$final_check_body_bg"
final_check_body_bg="$newcol"
colsel "persist_check_body_bg" "$persist_check_body_bg"
persist_check_body_bg="$newcol"
colsel "iso_test_body_bg" "$iso_test_body_bg"
iso_test_body_bg="$newcol"
}
########################################################################
########################################################################

function colsel {

newcol="$2"
ans=1
while [ "$ans" != "0" ]
do

ans=$(zenity --title="$version - '$1'" --color-selection --color="$newcol" \
--window-icon="/usr/share/icons/hicolor/48x48/apps/mkusb.png")

#read -p "selected colour=$ans (and string length=${#ans}). Is is what you expect? "

if [ "${ans:0:3}" == "rgb" ]
then
 newcol="$ans"
elif [ ${#ans} -eq 13 ]
then
 newcol="#${ans:1:2}${ans:5:2}${ans:9:2}"
elif [ ${#ans} -eq 7 ]
then
 newcol="$ans"
fi

 htmlbody="
<body style='background:$newcol;'>
$imgsrc
<!--
<span style='font-family:arial;font-size:20px;'><sup><b>
- mkusb -
</b></sup></span>
-->
<p style='font-family:arial;background:#d3d7cf;color:black;font-size:14px;'>
<br>
The <span style='color:#2252a0;'>$1</span> style is tested with this screen
<span style='color:#2252a0;'>colour contrast for text</span>
<br><br>
This is the <b>final checkpoint</b> '$1' before wiping and installing.
<br>
<span style='color:#cc0000;'>Please check again that it is the correct target device!
<br><br>
</p>
</span>
$arrow
</body>"

 (echo "$htmlbody") | zenity --text-info --html --filename=/dev/stdin \
--width=$(($wadd+720)) --height=$(($hadd+450)) \
--title "$version - Testpage for '$1' at Final checkpoint" \
--ok-label="Good colour" --cancel-label="Try again" \
--checkbox="Check this box if you are ready to go" 2>> "$zerrlog"

ans=$?
done

echo "saving the colour '$1=$newcol'"
echo "$1=$newcol" >> "$tgfile"
}

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

function zenitylegacy {

LANG=C

errout=$(mktemp)
echo "testing zenity in legacy mode" >> "$errout"

(echo "${version/mkusb/mkusb-legacy}") | zenity --text-info --filename=/dev/stdin \
--height=$(($hadd+120)) --title "" --timeout 2 2>> "$errout"

exitnr=$?
grep 'The owner of' "$errout"
sudoH=$?
if [ $sudoH -eq 0 ]
then
 echo "#####  Use  sudo -H mkusb  #####"
fi

if [ $exitnr -eq 0 ] || [ $exitnr -eq 5 ]
then
 zenityplug=true
elif [ $exitnr -eq 1 ]
then
 if test -s "$errout"
 then
  if [ $sudoH -ne 0 ]
  then
   zenityplug=false
  fi
 fi
else
 zenityplug=false
fi

if $zenityplug
then
 splashed=true
 legacy=true
 version="${version/mkusb/mkusb-legacy}"
 echo "legacy mode"
else
 echo " "
 echo "zenity does not work"
 echo " "
# echo "exitnr=$exitnr"
 cat "$errout"
 read -t 3
 exit
fi

LANG="$curlang"
rm "$errout"
}

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

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 "$distr"
} 

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

function mkusb_usage {

  echo "Usage:  # New: parameter p for persistent #"
  echo "Usage:  # New: wipe menu with several new options #"
  echo "---- Make a USB install device from ISO or image file --------"
  echo "sudo -H $0"
  echo "sudo -H $0 file.iso      # install a live only system"
  echo "sudo -H $0 file.iso p    # install a persistent live system"
  echo "sudo -H $0 \"quote file name (1) with special characters.iso\""
  echo "sudo -H $0 file.img"
  echo "sudo -H $0 file.img.gz"
  echo "sudo -H $0 file.img.xz"
  echo "---- Install from 'file.img.xz', show all mass storage devices"
  echo "sudo -H $0 file.img.xz all"
  echo "---- Clone a device (typically a CD drive or USB drive) ------"
  echo "sudo -H $0 /dev/sr0      # example of CD drive"
  echo "---- Wipe menu with several alternatives ---------------------"
  echo "sudo -H $0 wipe"
  read -p "---- Press the Enter key to get the next page "
  echo "---- Wipe the USB device (may take long time) ----------------"
  echo "sudo -H $0 wipe-whole-device"
  echo "---- Wipe the first megabyte (MibiByte)"
  echo "sudo -H $0 wipe-1        # show only USB devices"
  echo "sudo -H $0 wipe-1 all    # show all mass storage devices"
  echo "---- Help and Version ----------------------------------------"
  echo "$0 -h"
  echo "$0 -v"
}
#######################################################################
#######################################################################

function tweak_zws {

res=1
while [ $res -ne 0 ]
do
 wadd=$(zenity --entry --title="Modify window width" --height=200 \
 --text="Add width in pixels" --entry-text "$wadd")

 res=$(($wadd +1))
 res=$?
done
res=1
while [ $res -ne 0 ]
do
 hadd=$(zenity --entry --title="Modify window height" --height=300 \
 --text="Add height in pixels" --entry-text "$hadd")

 res=$(($hadd +1))
 res=$?
done
}

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

function about {

btitle="About $version"

message=\
"<center>
<h1>$version</h1>
<br>
mkusb - MaKe USB boot device<br>
author - sudodus alias Nio Wiklund<br>
https://help.ubuntu.com/community/mkusb<br>
<br>
Copyright 2014-2016 Nio Wiklund<br>
GPLv3: GNU GPL version 3<br>
http://gnu.org/licenses/gpl.html
</center><br>
This is free software: you are free to use, change and redistribute it.

There is NO WARRANTY, to the extent permitted by law.
</p>"

mkz_msg "$message" "--title=$btitle" "--width=$(($wadd+360))" "--height=$(($hadd+480))" "--cancel-label=man mkusb"
if [ $? -eq 1 ]
then
 if test -s /usr/share/man/man8/mkusb.8.gz
 then
  xterm -geometry 90x24 -fa default -fs 10 -bg '#ebeceb' -fg black -T 'man mkusb' -e man mkusb
 else
  zenity --info --text=\
"Install mkusb from the PPA to get the manual page.
See https://help.ubuntu.com/community/mkusb" 2>> "$zerrlog"
 fi
fi
}

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

function work_flow {

btitle="$version - Work flow (window sequences)"

message=\
"<h3>Installing new system - Work flow (window sequence)</h3>

menu: Starter menu (--> select source)<br>
file selector: Select source file<br>
menu: Back at Starter menu (--> install)<br>
Notice and overview<br>
menu: Select device - and go ahead<br>
Final checkpoint<br>
Work done :-)

<h3>'Isotesting' (when automatic identification of target drive)</h3>

{menu: Starter menu (--> select source)<br>
file selector: Select source file; or use default source file}<br>
menu: Starter menu (--> install)<br>
Directly to the final checkpoint<br>
Recloned :-)

<h3>Wiping</h3>

menu: Starter menu (--> wipe)<br>
Notice and overview<br>
menu: Select device - and go ahead<br>
Final checkpoint<br>
Work done :-)"

mkz_msg "$message" "--title=$btitle" "--width=$(($wadd+600))" "--height=$(($hadd+560))" "--cancel-label=man mkusb"
if [ $? -eq 1 ]
then
 if test -s /usr/share/man/man8/mkusb.8.gz
 then
  xterm -geometry 90x24 -fa default -fs 10 -bg '#ebeceb' -fg black -T 'man mkusb' -e man mkusb
 else
  zenity --info --text=\
"Install mkusb from the PPA to get the manual page.
See https://help.ubuntu.com/community/mkusb" 2>> "$zerrlog"
 fi
fi
}

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

function scrsizetest {

lines=$(tput lines)
cols=$(tput cols)

if [ $cols -lt 80 ] || [ $lines -lt 22 ]
then
 xtra="Drag & drop a corner to increase the size of the console"
message=\
"mkusb uses a <b>terminal window as console</b> for\n
output from the engine behind the curtains
<pre>
Terminal window size   = ${cols}x${lines} characters,
while recommended size = 80x22 or larger,
</pre>
and increased width will improve the display.<br><br>
$xtra"

 mkz_msg "$message" "--title=$version - $xtra" \
 "--width=$(($wadd+500))" "--height=$(($hadd+400))" "--cancel-label=Exit from mkusb"
 if [ $? -eq 1 ]
 then
  clean_mtab_n_colors_n_zerrlog
  rm "$zerrlog"
  exit
 fi
fi
}

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

function mkz_msg {

# Usage: mkz_msg <message> [option1] [option2] [option3]
# Usage: mkz_msg <message> [option1] [option2] [option3] [option4]
# mkz_msg "$message" "--title=$btitle" "--width=$(($wadd+640))" "--height=$(($hadd+400))" "--cancel-label='Quit'"
# mkz_msg "$message" "--title=$btitle" "--width=$(($wadd+640))" "--height=$(($hadd+400))"

#echo "legacy=$legacy"
#legacy=true           #  for testing legacy mode  ********************

if [ $# -eq 6 ]
then
 if ! "$legacy"
 then
  mkz_html "$1" "$2" "$3" "$4" "$5" "$6"
 else
  mkz_legacy "$1" "$2" "$3" "$4" "$5" "$6"
 fi
elif [ $# -eq 5 ]
then
 if ! "$legacy"
 then
  mkz_html "$1" "$2" "$3" "$4" "$5" 
 else
  mkz_legacy "$1" "$2" "$3" "$4" "$5" 
 fi
else
 if ! "$legacy"
 then
  mkz_html "$1" "$2" "$3" "$4"
 else
  mkz_legacy "$1" "$2" "$3" "$4"
 fi
fi
}

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

function mkz_html {

# Usage: mkz_msg <message> [option1] [option2] [option3]
# Usage: mkz_msg <message> [option1] [option2] [option3] [option4]
# mkz_msg "$message" "--title=$btitle" "--width=$(($wadd+640))" "--height=$(($hadd+400))" \
# "--cancel-label='Quit'" "--ok-label='Something Else'"
# mkz_msg "$message" "--title=$btitle" "--width=$(($wadd+640))" "--height=$(($hadd+400))"

message="$1"
message=${message//\\n/<br>}
#message=${message//\\Z4/<span style='color:#3262a0;'>}
message=${message//\\Z4/<span style='color:#2252a0;'>}
message=${message//\\Z1/<span style='color:#cc0000;'>}
message=${message//\\Z7/<span style='color:#ebeceb;'>}
message=${message//\\Zn/<\/span>}


if $persnote_flag
then
 if $liveonly
 then
  persnote="- live-only -"
  current_check_body_bg="$final_check_body_bg"
 else
  persnote="- persistent live -"
  current_check_body_bg="$persist_check_body_bg"
 fi
else
 persnote=""
fi
persnote_flag=false

htmlbody="
<!-- GREEN <body style='background:#b4df02;'> -->
<!-- RED   <body style='background:#cc0000;'> -->
<!-- BLUE  <body style='background:#3262a0;'> -->
<!-- ZenityGreyStrip <body style='background:#ebebeb;'> -->
<body style='background:#ebeceb;'>

$imgsrc
<span style='font-family:arial;font-size:32px;background:$current_check_body_bg'>
$persnote
</span>

<span style='font-family:arial;background:#ebeceb;color:black;font-size:14px;'>
<p>
<br>
$message
<br><br>
</p>
</span>
</body>"

if [ "$5" == "" ]
then
 (echo "$htmlbody") | zenity --text-info --html --filename=/dev/stdin \
 --ok-label="OK" \
 "$2" "$3" "$4" 2>> "$zerrlog"
elif [ "$6" == "" ]
then
 (echo "$htmlbody") | zenity --text-info --html --filename=/dev/stdin \
 --ok-label="OK" \
 "$2" "$3" "$4" "$5" 2>> "$zerrlog"
else
 (echo "$htmlbody") | zenity --text-info --html --filename=/dev/stdin \
 --ok-label="OK" \
 "$2" "$3" "$4" "$5" "$6" 2>> "$zerrlog"
fi

res=$?
#echo "$res"

if [ $res -eq 0 ]; then
# echo "OK"
 return 0
elif [ $res -eq 1 ]; then
# echo "Quit"
 return 1
# exit
else
 echo "Error"
# exit
fi
}

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

function mkz_legacy {

# Usage: mkz_msg <message> [option1] [option2] [option3]
# Usage: mkz_msg <message> [option1] [option2] [option3] [option4]
# mkz_msg "$message" "--title=$btitle" "--width=$(($wadd+640))" "--height=$(($hadd+400))" "--cancel-label='Quit'"
# mkz_msg "$message" "--title=$btitle" "--width=$(($wadd+640))" "--height=$(($hadd+400))"

message="$1"
message=${message//\\n/}
message=${message//\\Z4/}
message=${message//\\Z1/}
message=${message//\\Z7/}
message=${message//\\Zn/}
message=$(echo "$message"|sed -e 's/<[^<]*>//'g)

if [ "$5" == "" ]
then
 (echo "$message") | zenity --text-info --filename=/dev/stdin \
 --ok-label="OK" --window-icon="/usr/share/icons/hicolor/48x48/apps/mkusb.png" \
 "$2" "$3" "$4" 2>> "$zerrlog"
elif [ "$6" == "" ]
then
 (echo "$message") | zenity --text-info --filename=/dev/stdin \
 --ok-label="OK" --window-icon="/usr/share/icons/hicolor/48x48/apps/mkusb.png" \
 "$2" "$3" "$4" "$5" 2>> "$zerrlog"
else
 (echo "$message") | zenity --text-info --filename=/dev/stdin \
 --ok-label="OK" --window-icon="/usr/share/icons/hicolor/48x48/apps/mkusb.png" \
 "$2" "$3" "$4" "$5" "$6" 2>> "$zerrlog"
fi

res=$?
#echo "$res"

if [ $res -eq 0 ]; then
# echo "OK"
 return 0
elif [ $res -eq 1 ]; then
# echo "Quit"
 return 1
# exit
else
 echo "Error"
# exit
fi
}

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

function mkhelp {

# make help text

# echo "Collecting data for 'Help to select drive'"
 hlptxt="/tmp/help-mkusb.txt"
 > "$hlptxt"
 echo "<b>Put the file name within quotes</b>, if you get the following output:" >> "$hlptxt"
 echo "<br><code>bash: syntax error near unexpected token '('" >> "$hlptxt"
 echo "<br><br> " >> "$hlptxt"
 echo "sudo -H $0 \"quote file name (1) with special characters.iso\"" >> "$hlptxt"
 echo "</code>" >> "$hlptxt"
 echo "<pre>_______________________________________________</pre>" >> "$hlptxt"
 echo " " >> "$hlptxt"
 echo "<b>Collected data to help select target drive</b>" >> "$hlptxt"
 echo "<pre>_______________________________________________</pre>" >> "$hlptxt"
 echo " " >> "$hlptxt"
 echo "<b>list_drives</b>     # function built into $prgnam" >> "$hlptxt"
 echo "<pre>" >> "$hlptxt"
 list_drives >> "$hlptxt"
 echo "</pre>" >> "$hlptxt"
 echo "<b>df --sync|grep \"/dev/[^f]d\"|sort</b> #" >> "$hlptxt"
 echo "<pre>" >> "$hlptxt"
 df --sync|grep "/dev/[^f]d"|sort >> "$hlptxt"
 echo "</pre>" >> "$hlptxt"
 echo "<b>ls -l /dev/disk/by-id| grep [a-z]$|tr -s ' ' ' ' \\" >> "$hlptxt"
 echo "|cut -d ' ' -f 9,11|sort -k2|grep -e \^a -e \^u \\" >> "$hlptxt"
 echo "|sed 's#../..#/dev#'</b> # also empty mass storage devices" >> "$hlptxt"
 echo "<pre>" >> "$hlptxt"
 ls -l /dev/disk/by-id| grep [a-z]$|tr -s ' ' ' ' \
 |cut -d ' ' -f 9,11|sort -k2|grep -e \^a -e \^u \
 |sed 's#../..#/dev#' >> "$hlptxt"
 echo "</pre>" >> "$hlptxt"
 echo "<b>lsusb|sort -k 4,4 -k 1</b> #" >> "$hlptxt"
 echo "<pre>" >> "$hlptxt"
 lsusb|sort -k 4,4 -k 1 >> "$hlptxt"
 echo "</pre>" >> "$hlptxt"
 echo "<b>fdisk -lu 2>/dev/null|grep \"/dev/[^f]d\"|sort</b> #" >> "$hlptxt"
 echo "<pre>" >> "$hlptxt"
 fdisk -lu 2>/dev/null|grep "/dev/[^f]d"|sort >> "$hlptxt"
 echo "</pre>" >> "$hlptxt"
 echo "<b>parted -ls</b> #" >> "$hlptxt"
 echo "<pre>" >> "$hlptxt"
 parted -ls  >> "$hlptxt"
 echo "</pre>" >> "$hlptxt"
 echo "<b>blkid /dev/[^f]d??|sort</b> #" >> "$hlptxt"
 echo "<pre>" >> "$hlptxt"
 blkid /dev/[^f]d??|sort >> "$hlptxt"
 echo "</pre>" >> "$hlptxt"
 echo "<b>lsblk -o NAME,MODEL,FSTYPE,LABEL,MOUNTPOINT,SIZE,NAME /dev/[^f]d?</b> #" >> "$hlptxt"
 echo "<pre>" >> "$hlptxt"
 lsblk -o NAME,MODEL,FSTYPE,LABEL,MOUNTPOINT,SIZE,NAME /dev/[^f]d?\
  | sed 's/        1K /[extended] /'>> "$hlptxt"
 echo "</pre>" >> "$hlptxt"

 btitlh="$version - Help info to select drive"
 xtitle="Use Arrow PgUp PgDn Home End keys to scroll this help info"

 message=
 while read rtmp
 do
  message=\
"$message
$rtmp"
 done < "$hlptxt"
# echo "$message"

 mkz_msg "$message" "--title=$xtitle" "--width=$(($wadd+960))" "--height=$(($hadd+560))" "--cancel-label=Continue"
# mkz_msg "$message" "--title=$xtitle" "--width=$(($wadd+960))" "--height=$(($hadd+560))" "--cancel-label=About"
# if [ $? -eq 1 ]
# then
#  about
# fi
}

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

function list_drives {

# parameter $1 for usbonly (true/false)

cnt1=0
cnt2=0

tmpfil=$(mktemp)
ls -l /dev/disk/by-id| grep -e [a-z]$ -e mmcblk[0-9]$|tr -s ' ' ' '|cut -d ' ' -f 9,11 \
|sort -k2|grep -e \^a -e \^u -e \^m|sed 's#../..#/dev#' > "$tmpfil"

if [ "$distr" == "opensuse" ]
then
 ls -l /dev/disk/by-id| grep -e [a-z]$ -e mmcblk[0-9]$|tr -s ' ' ' '|cut -d ' ' -f 9,11 \
 |sort -k2|grep -e \^a -e \^u -e \^m -e \^scsi-S|grep -v \^scsi-SATA|sed 's#../..#/dev#' > "$tmpfil"
fi

while read name device
do
 cnt1=$(($cnt1 + 1))
 nam1[$cnt1]="${name%_*}"
nam1[$cnt1]=${nam1[$cnt1]:0:36}
 dev1[$cnt1]="$device"
# /bin/echo -e "${nam1[$cnt1]}\0011${dev1[$cnt1]}"
done < "$tmpfil"

lsblk -db /dev/[^f]d? /dev/mmcblk? 2> /dev/null|grep disk|tr -s ' ' ' ' \
| cut -d ' ' -f1-4 |sort > "$tmpfil"

while read device dum1 dum2 bytesize
do
 cnt2=$(($cnt2 + 1))
 dev2[cnt2]="$device"
 mbsize=$((($bytesize+500000)/1000000))
 gbsize=$((($bytesize+500000000)/1000000000))
 if [ $mbsize -lt 32000 ]
 then
  prsize[$cnt2]="${mbsize}MB"
 else
  prsize[$cnt2]="${gbsize}GB"
 fi
 device[$cnt2]="/dev/$device"
# echo "${device[$cnt2]}" "${prsize[$cnt2]}"
done < "$tmpfil"

rm "$tmpfil"

if [ $cnt1 -ge $cnt2 ]
then
 count=$cnt1
else
 count=$cnt2
fi
strsize=0
for (( i=1; i<=$count ; i++ ))
do
 if [ ${#nam1[$i]} -gt $strsize ]
 then
  strsize=${#nam1[$i]}
 fi
done
#echo $strsize
for (( i=1; i<=$count ; i++ ))
do
 addsize=$(($strsize - ${#nam1[$i]}))
 blank='                                                    '
 spacer=${blank:0:$addsize}
# echo $addsize
# echo "xxx${blank:0:$addsize}xxx"

 printsize=
 for (( j=1; j<=$count ; j++ ))
 do
#  echo "${dev1[$i]} ?==?  /dev/${dev2[$j]}"
  if [ "${dev1[$i]}" ==  "/dev/${dev2[$j]}" ]
  then
   printsize="${prsize[$j]}"
#   echo "printsize=$printsize"
  fi
 done

 if [ "$printsize" != "" ]
 then
  string="Name: ${nam1[$i]}${spacer}  Dev: ${dev1[$i]}  Size: $printsize"
  if [ "$1" == "true" ]
  then
   usbstring="${string/Name\:\ usb\-/USB: }"
   mmcstring="${string/Name\:\ mmc\-/MMC: }"
   scsistring="${string/Name\:\ scsi\-S/SCSI: }"
   if [ "$usbstring" != "$string" ]
   then
    /bin/echo -e "$usbstring"
   elif [ "$mmcstring" != "$string" ]
   then
    /bin/echo -e "$mmcstring"
   elif [ "$scsistring" != "$string" ]
   then
    /bin/echo -e "$scsistring"
   fi
  else
    /bin/echo -e "$string"
  fi
 fi
done
}

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

function check_packages {

# check pipe view and offer installation

if ! "$checked_pack"
then
 checked_pack=true

 which pv > /dev/null
 if [ "$?" == "0" ]
 then
  pvplug=true
 else
  find_installer
  /bin/echo -e \
  "The program 'pv' can show the progress during the installation."
  asker "The program 'pv' can show the progress during the installation.

Do you want to install it? (y/N)"
  if [ $? -eq 0 ]
  then
   echo ${inst_prog[@]} pv
   ${inst_prog[@]} pv
  fi
  which pv > /dev/null
  if [ "$?" == "0" ]
  then
   pvplug=true
  else
   pvplug=false
  fi
 fi
# echo $pvplug

# check menu packages and offer installation

 menu_package_installer needs zenity "mkusb-nox works without it."
 if $liveonly
 then
#  menu_package_installer wants grub-install "needed in order to install 'persistent live'." grub-pc
  menu_package_installer wants gdisk "needed in order to install 'persistent live'."
 else
  get_grub_pc
  menu_package_installer needs gdisk "needed in order to install 'persistent live'."
  menu_package_installer needs rsync "needed in order to install 'persistent live'."
 fi
 menu_package_installer wants wmctrl "only in order to install 'persistent live'."
 menu_package_installer wants xterm "mkusb-legacy.desktop works without it"
# menu_package_installer wants smartctl "mkusb can work without it." smartmontools

# test if zenity is available

 zenitytest

 if ! $zenityplug
 then
  zenitylegacy
 fi

# test text screen size

 scrsizetest

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 and wmctrl need 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 [and wmctrl(?)] 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 "mkusb $1 the program '$2': $3"
 asker "mkusb $1 the program '$2': $3 Install?"
 if [ $? -eq 0 ]
 then
  if [ ${inst_prog[1]} == "apt-get" ]
  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
   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
  echo "$version $1 $2 but it is not installed."
  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_n_colors_n_zerrlog {

LANG=C

cd "$startdir"

tmp1fil=$(mktemp)

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

#if test -f "$HOME/.dialogrc"
#then
# sed -i 's/screen_color =.*/screen_color = (CYAN,BLUE,ON)/' "$HOME/.dialogrc"
#fi
#sed -i 's#^*VT100.color4: .*#*VT100*color4: blue2#' /etc/X11/app-defaults/XTerm-color
#sed -i 's#^*VT100.color1: .*#*VT100*color1: red3#' /etc/X11/app-defaults/XTerm-color
#sed -i 's#^*VT100.color7: .*#*VT100*color7: gray90#' /etc/X11/app-defaults/XTerm-color

if test -s "$zerrlog"
then
 zenity --question --timeout 1 --text "Check zenity error log?" \
 --width=$(($wadd+460)) --height=$(($hadd+200)) \
 --ok-label "No" --cancel-label="Yes" 2>> "$zerrlog"
 if [ $? -eq 1 ]
 then
  sync
  zenity --text-info --filename="$zerrlog" 2>> /dev/null
 fi 
fi
curlang="$LANG"
echo "Cleanup after mkusb 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 select_device {

# version for mkusb (ported from OBI)

# make command and run command, 'here we go'

ans=-1
choice=1
target=
LC_ALL=C
LANG=C
tmpstr=

ltest0=$(grep -m 1 " / " /etc/mtab|cut -d ' ' -f 1)
if [ "$ltest0" == "/cow" ] || [ "$ltest0" == "aufs" ] || [ "$ltest0" == "rootfs" ]
then
 ltest1=$(grep -m 1 ' /isodevice' /etc/mtab|cut -c 5-8)
 if [ "$ltest1" != "" ]
 then
  livedrive=$ltest1
 else
  ltest1=$(grep -m 1 ' /cdrom' /etc/mtab|cut -c 5-8)
  if [ "$ltest1" != "" ]
  then
   livedrive=$ltest1
  else
   ltest1=$(grep -m 1 ' /livecd' /etc/mtab|cut -c 5-8)
   if [ "$ltest1" != "" ]
   then
    livedrive=$ltest1
   else
    ltest1=$(grep -m 1 ' iso9660' /etc/mtab|grep -v ' /media'|grep -v ' /mnt'|cut -c 5-8)
    if [ "$ltest1" != "" ]
    then
     livedrive=$ltest1
    else
     ltest1=$(grep -m 1 ' iso9660' /etc/mtab|grep ' /mnt-system'|cut -c 5-8)  # knoppix
     if [ "$ltest1" != "" ]
     then
      livedrive=$ltest1
     else
      ltest1=$(df 2>/dev/null|grep -m 1 " /$" |cut -c 5-8)  # mageia
      if [ "$ltest1" != "" ] && test -b "/dev$ltest1"
      then
       livedrive=$ltest1
      else
       ltest1=$(lvm pvdisplay|grep 'PV Name'|sed 's/.* //'|cut -c 5-8)  # fedora
       ltest2=$(df 2>/dev/null|grep -m 1 " /$" |sed 's/ .*//')
       if [ "$ltest1" != "" ] && [ "$ltest2" == "/dev/mapper/fedora-root" ]
       then
        livedrive=$ltest1
        if ! test -b "/dev$livedrive"
        then
         livedrive="not_found"
        fi
       fi
      fi
     fi
    fi
   fi
  fi
 fi
elif [ "${ltest0/\/dev\/[^f]d}" != "" ]
then
 livedrive=$(df 2>/dev/null|grep -m 1 /$ |cut -c 5-8)
else
 livedrive=$(df 2>/dev/null|grep -m 1 " /$" |cut -c 5-8)
 if ! test -b "/dev$livedrive"
 then
  livedrive="not_found"
 fi
fi
#echo ltest0=$ltest0
#echo ltest1=$ltest1
#echo ltest2=$ltest2
 echo "Booted from: /dev$livedrive"

 if ! $legacy
 then
 tmpstart='<table style="width:100%"> <tr>
 <td>Name:  </td><td>Device:  </td><td>Size:  </td>'
# tmptbl=$(list_drives|sed 's/$/\<br\>/')
 tmptbl=$(list_drives|sed -e 's/$/\<br\>/' -e 's#Name:#<tr><td>#g' \
 -e 's#Dev:#</td><td>#g' -e 's#Size:#</td><td>#g' -e 's#$#</td></tr>#g')
 tmpend="</table>"
 tmpstr="$tmpstart
$tmptbl $tmpend"
 else 
  tmpstr="
$(list_drives)"
 fi
#echo $tmpstr
#read -p "press enter to continue"

tmpstr="$tmpstr\n

Booted from: /dev$livedrive"

 message="$spec_src\n\n

\Z1Notice: the target device will be completely overwritten\Zn\n
Help selecting the target device is available via the Starter -- Help menu\n
\Z1Please close any other applications accessing your target device.\Zn\n
This will ensure that mkusb has exclusive access to it.\n
(Example: A terminal window can prevent unmounting the target device.)\n\n
$tmpstr"

 btitle="$version - Notice and overview"

 mkz_msg "$message" "--title=$btitle" "--width=$(($wadd+640))" "--height=$(($hadd+560))" \
 "--cancel-label=Quit" "--ok-label=Select target device in the next window"
 if [ $? -eq 1 ]
 then
  ans=0
  LANG="$curlang"
  return 1
 fi

while [ "$ans" == "u" ] || [ $ans -lt 0 ]
do

#echo "usbonly=$usbonly"

 if $usbonly; then ufl=usb; else ufl=d;fi


 aind=0
 bind=0
 unset adev
 unset atxt
 unset bvar

#echo "usbonly=$usbonly"
#list_drives "$usbonly"|tr -s ' ' ' '|cut -d ' ' -f 4
#read -p 'Press enter to continue at list_drives'
sync 
for j in $(list_drives "$usbonly"|tr -s ' ' ' '|cut -d ' ' -f 4)
 do
# echo "j=$j"
  busy=0

  if [ "$j" == "$source" ]
  then
   echo "$j is busy; it is the source device"
   busy=1
  fi

  infstb=$(for k in $(grep ^UUID /etc/fstab 2>/dev/null|tr '=' ' '|cut -d ' ' -f2);do blkid /dev/[^f]d??|grep -m1 $k;done|grep $j)
  if [ $? -eq 0 ] 
  then
   echo "$j is busy; in fstab"
   busy=1
#  echo "$infstb"
  fi
  if [ $busy -eq 0 ]
  then
   for k in $(df --sync 2>/dev/null|grep "$j" |tr -s ' ' '\t'|cut -f1)
   do umount "$k" 2>/dev/null; if [ "$?" != "0" ];then busy=1;fi ;done
   if [ $busy -eq 1 ]
   then
    echo "$j is busy; cannot be unmounted. Close any program that is using
this device if you want to select and use it as a target for mkusb (maybe
change directory if a terminal window is using the partition)!"
   fi
  fi
  tj="$(list_drives $usbonly|grep $j)"
#  echo "k=$k"
#  echo "busy=$busy"
#  echo "${tj:0:7}"
#  echo "${tj}"
#  read -p "select-device at Warning and Error"
  if [ "${tj:1:7}" == "Warning" ] || [ "${tj:1:5}" == "Error" ]
  then
    tj=$(fdisk -lu "$j" 2>/dev/null|grep "$j":|sed s/\,\ .*//)
  fi

  if [ "$j" == "/dev$livedrive" ]
  then
   adev[$aind]="q"
   atxt[$aind]="${tj/Name:/Live:}"
   aind=$(($aind + 1))
  elif [ "$j" == "$source" ]
  then
   adev[$aind]="q"
   atxt[$aind]="${tj/Name:/Source:}"
   aind=$(($aind + 1))  
  elif [ "$busy" == "1" ]
  then
   adev[$aind]="q"
   atxt[$aind]="${tj/Name:/Busy:}"
   aind=$(($aind + 1))
  else
   adev[$aind]="$j"
   atxt[$aind]="$tj"
   aind=$(($aind + 1))
  fi
 done
 adev[$aind]="u"
 if $usbonly
 then
  atxt[$aind]="toggle USB-only; show all drives"
 else
  atxt[$aind]="toggle USB-only; hide other drives"
 fi
 aind=$(($aind + 1))
 adev[$aind]="q"
 atxt[$aind]="quit installing"
 aind=$(($aind + 1))
 for (( xi=0; xi < $aind ; xi++ ))
 do
  if [ "${adev[$xi]}" == "u" ]
  then
   bvar[$bind]="u"
  elif [ "${adev[$xi]}" == "q" ]
  then
   bvar[$bind]="q"
  else
   bvar[$bind]=$(($xi+1))
  fi
  bind=$(($bind + 1))
  bvar[$bind]="${atxt[$xi]}"
  bind=$(($bind + 1))
 done

# select device - the Mkusb button to go

#echo "aind=$aind"
#echo "${bvar[@]}"
#read -p 'stop at Go ahead menu'

btitle="$version - Select device - and go ahead"

  ans=$(zenity --list --width=$(($wadd+640)) --height=$(($hadd+400)) --title="$btitle" \
--window-icon="/usr/share/icons/hicolor/48x48/apps/mkusb.png" \
--column="Hotkey" --column="Select device or toggle USB-only" \
"${bvar[@]}" 2>> "$zerrlog")

 ans=${ans:0:1}          # fix for buggy(?) zenity --list in trusty

echo "ans=$ans"

 if [ "$ans" == "u" ]
 then
  choice=1
  if $usbonly
  then
   usbonly=false
  else
   usbonly=true
  fi
 elif [ "$ans" == "q" ] || [ "$ans" == "" ] || [ $ans -lt 0 ]
 then
  ans=0
  return 1
 else
  choice=$(($ans - 1))
  target="${adev[$choice]}"
  cmdsav="${atxt[$choice]}"
 fi
# echo "ans=$ans at end of while loop"
done

# here we go 'go_on'

if [ "$source" == "/dev/zero" ]
then
 doing="wiping\n\n"
 if [ "$makepart" != "" ]
 then
  doing="wiping and making partition table on\n\n"
 fi
else
 doing="installing the operating system from\n
\Z4$srcorig\Zn\n
\n
to "
fi



#echo "select_device: $system" "$imagefile" "$target"
# echo "$cmdsav"

cmdsav="${cmdsav/USB\:\ }"
cmdsav="${cmdsav/Name\:\ usb\-}"
cmdsav="${cmdsav/Name\:\ ata\-}"
cmdsav="${cmdsav/Dev\:}"
cmdsav="${cmdsav/Size\:}"
cmdsav=$(tr -s ' ' ' ' <<< "$cmdsav")
cmdsav=$(sed 's/ /  /g' <<< "$cmdsav")

#echo "$cmdsav"
#read -p 'stop'
LANG="$curlang"

btitle="$version - Select device - final checkpoint"

if ! $legacy
then
 doing=${doing//\\n/<br>}
 doing=${doing/\\Z4/<span style='color:#2252a0;'>}
 doing=${doing/\\Zn/<\/span>}

persnote=
if [ "$source" != "/dev/zero" ] && [ "${source/.iso}" != "$source" ]
then
 if $liveonly
 then
  persnote="<br>Installing a <span style='color:#2252a0;'>live only</span> system<br>"
  current_check_body_bg="$final_check_body_bg"
 else
  persnote="<br>Installing a <span style='color:#2252a0;'><b>persistent</b></span> live system<br>"
  current_check_body_bg="$persist_check_body_bg"
  btitle="$btitle - persistent"
 fi
else
 current_check_body_bg="$final_check_body_bg"
fi
if [ "$systag" != "" ]
then
 systag="The system tag <span style='color:#2252a0;'>$systag</span><br>
was found in the iso-file.<br>
<br>"
fi
 htmlbody="
<body style='background:$current_check_body_bg;'>
$imgsrc
<!--
<span style='font-family:arial;font-size:20px;'><sup><b>
- mkusb -
</b></sup></span>
-->
<p style='font-family:arial;background:#d3d7cf;color:black;font-size:14px;'>
<br>
"$systag"
$prgnam is ready to start ${doing}the target
<span style='color:#2252a0;'>$cmdsav</span>
<br>$persnote<br>
This is the <b>final checkpoint</b> before wiping and installing.
<br>
<span style='color:#cc0000;'>Please check again that it is the correct target device!
<br><br>
</p>
</span>
$arrow
</body>"

 (echo "$htmlbody") | zenity --text-info --html --filename=/dev/stdin \
--width=$(($wadd+640)) --height=$(($hadd+500)) \
--title "$btitle" \
--ok-label="Go" --cancel-label="Quit" \
--checkbox="Check this box if you are ready to go" 2>> "$zerrlog"
else
 doing=${doing//\\n}
 doing=${doing/\\Z4}
 doing=${doing/\\Zn}

 final_checkpoint_legacy "$doing"
fi
ans=$?

if [ "$ans" != "0" ]
then
 return 1
fi

#checkpoint_question

if [ "$?" != "0" ]
then
 return 1
fi

swapoff "$target"* 2>/dev/null
sync

# echo "ans=$ans at end of select_device"

# echo target="$target"
# echo "at end of select_device"
#  exit  #-------------------------------------------  skarpt läge
}

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

function final_checkpoint_legacy {

persnote=
if [ "$source" != "/dev/zero" ] && [ "${source/.iso}" != "$source" ]
then
 if $liveonly
 then
  persnote="Installing a 'live only' system
"
 else
  persnote="Installing a *persistent* live system
"
  btitle="$btitle - persistent"
 fi
fi
if [ "$systag" != "" ]
then
 systag="The system tag '$systag'
was found in the iso-file.
"
fi

message=\
"$systag
$prgnam is ready to start $1 the target '$cmdsav'

$persnote
This is the Final Checkpoint before wiping and installing.
Please check again that it is the correct target device!
______________________________________________________________________
Check the box down there if you are ready to go!"

echo "$message"|zenity --text-info --title="$btitle" \
--checkbox "Check this box if you are ready to go" \
--ok-label="OK" --cancel-label="Quit" \
--window-icon="/usr/share/icons/hicolor/48x48/apps/mkusb.png" \
--width=600 --height=450 --filename="/dev/stdin" 2>> "$zerrlog"

if [ $? -ne 0 ] || [ "${ans:0:1}" == "Q" ]
then
 ans="1"
else
 ans="0"
fi

echo "Result: ans=$ans"
return $ans
}

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

function mkcmd_runcmd {

# 6 parameters:
#        mkcmd_runcmd "$1" "$source" "$system" "$cnt" "$doing_this" "$result"
#echo In mkcmd_runcmd "$1" "$source" "$system" "$cnt" "$doing_this" "$result"

# make command and run command, 'here we go'

 LANG=C

 if [ "$target" == "" ]
 then
  echo "No target"
  exit
 elif [ "$source" == "" ]
 then
  echo "No source"
  exit
 else
  swapoff "$target"* 2>/dev/null
  sync

# the command line is implemented 

  echo " "

# build target and write 'a first line' to the terminal ...

  if [ "$1" == "wipe-whole-device" ] || [ "$1" == "/dev/zero" ]
  then
   doing_this="Wiping the whole device $target ..."
  elif [ "$1" == "wipe-1" ] || [ "$1" == "wipe1" ]
  then
   if [ "${makepart:0:3}" == "gpt" ]
   then
    doing_this="Making GUID partition table on $target ..."
   elif [ "$makepart" == "msdos" ]
   then
    doing_this="Making MSDOS partition table and FAT32 partition on $target ..."
   fi
   doing_this="Wiping the first megabyte (MibiByte) of $target ... :"
  else
   doing_this="Installing $1 to $target ..."
  fi
  echo "$doing_this"
  echo " "  

# build beginning of command (read the source) and calculate size

# current directory changed to that of the source file, so

  if test -f "$source"
  then
   source=${source##*/}
   ii="${1##*/}"
  else
   ii="$1"  
  fi
#  echo "source=$source"
#  echo "ii=$ii"

  if [ "${source%/*}" == "/dev" ]
  then
   readsrc="< $source"
   size=
  elif [ "$source" == "$ii" ]
  then

# double quotes makes source file name work with some special characters

   source=\""$source"\"

   if [ "${ii%.iso}" != "$ii" ] || [ "${ii%.img}" != "$ii" ]
   then
    size=$(wc -c "$ii"|cut -d ' ' -f 1)
    readsrc="< $source"
   elif [ "${ii%.img.[gx]z}" != "$ii" ]
   then
    if [ "${ii%.img.gz}.img.gz" == "$ii" ]
    then
     size=$(gzip -l "$ii"|grep "${ii/.gz}"|tr -s ' ' ' '|sed s/^\ //|cut -d ' ' -f 2)
     readsrc="zcat $source |"
    else
#     si10=$(xz -l "$ii"|grep "${ii/.xz}"|tr -s ' ' ' '|sed s/^\ //| \
#            cut -d ' ' -f 5|sed 's/\.//')
#     sitr=$(((${si10}+5)/10))
#     powr=$(xz -l "$ii"|grep "${ii/.xz}"|tr -s ' ' ' '|sed s/^\ //| \
#            cut -d ' ' -f 6|sed -e s/..$//)
#     size=$sitr$powr
     size=$(xz --robot --list "$ii" | tail -n1 | cut -f5)
     readsrc="xzcat $source |"
    fi
   fi
   size="-s ${size,,}"
  else
   readsrc="< $source"
   size=
  fi
  if [ "$1" == "wipe-whole-device" ] || [ "$1" == "/dev/zero" ]
  then
   size=$(lsblk -dnbo SIZE "$target")
   size="-s ${size,,}"
#   echo "size=$size"
  fi

# build pvpipe (if available)

  if $pvplug
  then
   pvpipe="pv -n $size |"
  else
   pvpipe=
  fi

#  echo "\$1=$1"
#  echo "source=$source"
#  echo "target=$target"
#  echo "bs=$bs"
#  echo "cnt=$cnt"
#  echo "pvplug=$pvplug"
#  echo "size=$size"
#  echo "pvpipe=$pvpipe"
#  echo "readsrc=$readsrc"

#  cmdfile=$(mktemp)

  cmdline="$readsrc $pvpipe dd bs=$bs $cnt of=$target"

#  echo "$cmdline"|tee $cmdfile
#  echo "$cmdline"
#  echo "Please wait for sync (flushing file system buffers to the device)"
#  echo "until 'Done' is written ..."

# rm "$cmdfile"; exit

  gpt_zap "$target"
  do_n_show "$cmdline"

#  bash $cmdfile

# maybe make partition table and file systems

  sig=$?

  if [ "$source" == "/dev/zero" ]
  then
   if [ "$makepart" == "msdos" ]
   then
    gpt_zap "$target"
    mk_msdos 
   elif [ "$makepart" == "gpt_skel" ]
   then
    mk_gpt_skel
   elif [ "$makepart" == "gpt_ntfs" ]
   then
    mk_gpt_ntfs
   elif [ "$makepart" == "gpart" ]
   then
    mk_gpart
   fi
  fi

  if [ $sig -eq 0 ]
  then
   result="Done :-)"
  elif [ "$1" == "wipe-whole-device" ]
  then
   result="Done, but you should also
check for the line 'dd: error writing '$target': No space left on device',
which means that the whole device is wiped. (Look in the terminal window
or the log file ~/mkusb.log) "
  else
   result="Failed :-("
  fi
  echo "Syncing the device ..."
#  rm "$cmdfile"
  sync
  echo "$result"
 fi

 LANG="$curlang"
}

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

function usage_prep_final {

#echo "usage_prep_final"
#echo "\$1=$1"
#echo "\$#=$#"

bs=4096
count=256
cnt=
target=
string1=
string2=

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

check_file "$1"

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

# check  program packages, offer installation and show a splash screen

check_packages

# prepare for questions using zenity

btitle=
xtitle="***  Notice: the device will be completely overwritten  ***"
question=

if [ ${#1} -lt 70 ]
then
 width=80
else
 width=$(( ${#1} +10 ))
fi

#echo "width=$width"

# cd to source file directory to keep partition mounted

#if [ "$source" != "/dev/zero" ]
if test -f "$source"
then
 if [ "${source%/*}" != "$source" ]
 then
  cd "${source%/*}"
 fi
 source="${source##*/}"
fi
#echo "current dir=$PWD"

############################################################## same iso

# check if updating 'the same' iso image

############################################################## same iso

if [ "${1/.iso}.iso" == "$1" ] && "$liveonly"
then
  same_iso
fi

# update iso image (live-only cloned system)

if [ "$target" != "" ]
then
# echo "target=$target"

 tgd=$(list_drives|grep "$target")
 btitle="$version - Update iso image (from new iso file)"

# if "$legacy"     # testing legacy
 if ! "$legacy"
 then

question=${question//\\n/<br>}
question=${question/\\Z4/<span style='color:#2252a0;'>}
question=${question/\\Zn/<\/span>}

question="Ready to update ISO image<br>
Source iso-file: <span style='color:#2252a0;'>$srcorig</span><br><br>
$question<br><span style='color:#2252a0;'>
$tgd</span><br><br>
Update from the source iso-file to the device <span style='color:#cc0000;'>${target}</span> ?"
question="${question//\\n/<br>}"

htmlbody="
<body style='background:$iso_test_body_bg;'>
$imgsrc
<!--
<span style='font-family:arial;font-size:20px;'><sup><b>
- mkusb -
</b></sup></span>
-->
<p style='font-family:arial;background:#d3d7cf;color:black;font-size:14px;'>
<br>
<b>ISO testing: <span style='color:#cc0000;'>$xtitle</span></b>
<br><br>
$question
<br><br>
</p>
</span>
$arrow
</body>"

(echo "$htmlbody") | zenity --text-info --html --filename=/dev/stdin \
--width=$(($wadd+640)) --height=$(($hadd+440)) \
--title "$btitle" \
--ok-label="Go" --cancel-label="Quit" \
--checkbox="Check this box if you are ready to go" 2>> "$zerrlog"
 else
question=${question//\\n}
question=${question/\\Z4}
question=${question/\\Zn}
question="Ready to update ISO image
Source iso-file: $srcorig

$question
$tgd

'flash/burn/restore' from the source iso-file to the device ${target} ?"

textbody="ISO testing: $xtitle

$question"

(echo "$textbody") | zenity --text-info --filename=/dev/stdin \
--width=$(($wadd+640)) --height=$(($hadd+400)) \
--title "$btitle" \
--ok-label="Go" --cancel-label="Quit" \
--window-icon="/usr/share/icons/hicolor/48x48/apps/mkusb.png" \
--checkbox="Check this box if you are ready to go" 2>> "$zerrlog"

 fi
 ans=$?
 persnote_flag=false
 if [ "$ans" == "0" ]
 then
  busy=0
  for k in $(df --sync 2>/dev/null|grep "$target" |tr -s ' ' '\t'|cut -f1)
   do umount "$k"; if [ "$?" != "0" ];then busy=1;fi; done
#   echo "busy=$busy"
#   echo "k=$k"
  if [ "$busy" == "1" ]
  then
   echo "Could not unmount $target because file system on device is busy :-("
   question="Could not unmount $target because file system on device is busy :-("

   mkz_msg "$question" "--title=$btitle" "--width=$(($wadd+640))" "--height=$(($hadd+400))" "--cancel-label=Exit from mkusb"
   if [ $? -eq 1 ]
   then
    ans=q
    return 1
   fi

   ans=0
   return 1
  else
   if $pvplug
   then
#    echo "pv \"$source\"| dd of=$target bs=$bs ..."
    do_n_show "pv -n \"$source\"| dd of=\"$target\" bs=$bs"
   else
    echo "dd if=\"$source\" of=$target bs=$bs ..."
    dd if="$source" of="$target" bs=$bs
   fi
   echo "syncing the drive ..."
   sync
   xtitle=
   echo "The $string1 USB device is updated  :-)"
   question="The  \Z4$string1\Zn <span style='background:\#b4df02;'> USB device is updated  :-)</span>

\n\n\Z4$tgd\Zn"

   btitle="$version - Work done with ${target} :-)"

   mkz_msg "$question" "--title=$btitle" "--width=$(($wadd+640))" "--height=$(($hadd+400))" "--cancel-label=Exit from mkusb"
   if [ $? -eq 1 ]
   then
    ans=q
    return 1
   fi
  fi
 fi 
else

# other alternatives: wipe or clone an iso, img.gz, img.xz file

 if [ "$source" == "/dev/zero" ]
 then
  btitle="$version - Wipe a mass storage device"
  question="Do you want to wipe a mass storage device (typically USB drive)?"
  if [ "$makepart" != "" ]
  then
   question="Do you want to wipe a device and make a new partition table and file system?"
  fi
 elif [ "${1%/*}" == "/dev" ]
 then
  btitle="$version - Clone a device"
  question="Do you want to clone a device (typically a CD drive to a USB drive)?"
 elif [ "${1/.iso}.iso" == "$1" ]
 then
  btitle="$version - Install iso file"
  if [ "$string1" != "" ]
  then
   echo "$string1 _not_ in any possible target drive"
#   question="$question but \Z4not\Zn in any possible target drive"
  fi
  question="$question \n
\Z4$1\Zn\n
\n
Select a target device in the next window!"
 elif [ "${1/.img}.img" == "$1" ]
 then
  btitle="$version - Install (uncompressed) image file"
question="Do you want to clone the (uncompressed) image file\n
\Z4$1\Zn\nto the target device (to be selected in the next window)?"
 elif [ "${1/.img.gz}.img.gz" == "$1" ] || [ "${1/.img.xz}.img.xz" == "$1" ]
 then
  btitle="$version - Install compressed image file"
question="Do you want to clone the compressed image file\n
\Z4$1\Zn\nto the target device (to be selected in the next window)?"
 else
  echo "usage_prep_final: bad choice of source file -- exit"
  ans=0
  return 1
 fi

# echo "$width"

 if $liveonly
 then
  spec_src="$question"
 else
  spec_src="Source file:\n
$question"
 fi

# mkz_msg "$question" "--title=$btitle" "--width=$(($wadd+640))" "--height=$(($hadd+400))" "--cancel-label=Quit"
# ans=$? 

ans=0           # added line to continue without getting OK from mkz_msg

 if [ $ans -eq 1 ]
 then
  ans=0
  return 1
 elif [ $ans -eq 0 ]
 then

# select target drive, make command and run command

#  echo select_device "$2"
  select_device
  if [ $? -eq 0 ]
  then
   if $liveonly || [ "$source" == "/dev/zero" ]
   then
#   echo mkcmd_runcmd "$1" "$source" "$system" "$cnt" "$doing_this" "$result"
         mkcmd_runcmd "$1" "$source" "$system" "$cnt" "$doing_this" "$result"
   else
    grub_n_iso "$source" "$target" "$result"
    doing_this="installing a persistent live system ..."
   fi
  else
   ans=0
   return 1
  fi

  if [ "${1/.iso}.iso" != "$1" ]
  then
   LANG=C
   gpt_fix "$target"
   LANG="$curlang"
  fi
  
# final screen

  if $liveonly || [ "$source" == "/dev/zero" ]
  then
   btitle="$version - Work done with ${target} :-)"
  elif ! $liveonly
  then
   question="Source file:\n
$question"
  fi
  if [ "${result:0:4}" == "Done" ]
  then
   unmount_unplug="The target device is unmounted and can be unplugged."
  else
   unmount_unplug="Unmount the target drive manually if necessary!"
  fi
  xtitle=
  tgd=$(list_drives|grep "$target")
  final="${question/Select a target device in the next window!}"
  final="${final/Do you want to clone/Cloning}"
  final="${final/ (to be selected in the next window)}"
  final="${final/\?}"

  final="$final

 <p style='background:\#b4df02;'>$doing_this\n
... $result<p>\n\n

${unmount_unplug}\n
\Z4$tgd\Zn"
  if [ "$source" == "/dev/zero" ]
  then
    final="$final\n
You may need to \Z1unplug & replug the drive or reboot\Zn \n
for the kernel to see that the drive is wiped."
  fi
  mkz_msg "$final" "--title=$btitle" "--width=$(($wadd+640))" "--height=$(($hadd+400))" "--cancel-label=Exit from mkusb"
  if [ $? -eq 1 ]
  then
   ans=q
   return 1
  fi
 fi
fi
}

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

function same_iso {

iso=$(mktemp -d)
drv=$(mktemp -d)
#echo "$iso"
#echo "$drv"
#echo "$source"
 
echo "The iso file SHOULD BE loop mounted on a temporary file READ-ONLY:"
sleep 0.5
umount "$iso" >/dev/null 2>&1
modprobe loop 2>&1 # for debian jessie
sync
mount -o loop -t auto "$source" "$iso" 2>&1

disk_name_type=""

tmpstr=$(grep -i -e ^default -e label "$iso"/{*,*/*,*/*/*}.cfg 2>/dev/null \
|sed -e s/.*cfg://|head -n2| tr '\n' '|')
if [ "$tmpstr" != "" ]
then
 disk_name_type="label"
 string1="$tmpstr"
fi
tmpstr=$(grep -i -e title "$iso"/{*,*/*,*/*/*}.cfg 2>/dev/null|sed -e s/.*cfg://|head -n1)
if [ "$tmpstr" != "" ]
then
 disk_name_type="title"
 string1="$tmpstr"
fi
tmpstr=$(grep -i version "$iso"/{*,*/*,*/*/*}.cfg 2>/dev/null|sed -e s/.*cfg://|head -n1)
if [ "$tmpstr" != "" ]
then
 disk_name_type="version"
 string1="$tmpstr"
fi
tmpstr=$(grep -i -e Architectures -e Origin -e suite -e version \
"$iso"/dists/*/Release 2>/dev/null|head -n4|sed 's/.*: *//'| tr '\n' ' ')
if [ "$tmpstr" != "" ]
then
 disk_name_type="debian"
 string1="$tmpstr"
fi
tmpstr=$(grep 'This is an installation system for Ubuntu' \
 "$iso"/f1.txt 2>/dev/null|sed -e s/.*Ubuntu/Ubuntu/)
if [ "$tmpstr" != "" ]
then
 disk_name_type="mini"
 string1="$tmpstr"
fi
tmpstr=$(grep DISKNAME "$iso"/README.diskdefines 2>/dev/null|sed -e s/.*DISKNAME\ *//)
if [ "$tmpstr" != "" ]
then
 disk_name_type="desktop"
 string1="$tmpstr"
fi

echo "disk_name_type=$disk_name_type"
# echo "string1=$string1"

if [ "$string1" != "" ]
then
 echo "$string1 _found_ in iso-file"
 systag="$string1"
 question="The system tag \Z4$string1\Zn\n
was found in the iso-file"
else
 echo "No disk-name string found in iso-file"
 question="No disk-name string found in the iso-file"
fi
sleep 0.5
umount "$iso"
rmdir "$iso"
sync

# Try to unmount partitions except swap partitions, and consider
# drives with an active swap partition busy, 'variable bizz'

#echo "usbonly=$usbonly ------------------------------------------"

for i in $(list_drives "$usbonly"|tr -s ' ' ' '|cut -d ' ' -f 4)
do
 bizz=false

 infstb=$(for j in $(grep ^UUID /etc/fstab|tr '=' ' '|cut -d ' ' -f2);do blkid /dev/[^f]d??|grep -m1 $j;done|grep $i)
 if [ $? -eq 0 ] 
 then
#  echo "$i is busy; in fstab"
  bizz=true
#  echo "$infstb"
 fi
 if ! $bizz
 then
  for j in $(blkid ${i}*|grep -v 'TYPE="swap"'|cut -d : -f 1)
  do
   umres=$(umount $j 2>&1|grep umount:|sed 's/.*: //')
#  echo "$j: umres=$umres"
   if [ "$umres" == "device is busy." ]
   then
    bizz=true
   fi
  done
  for j in $(blkid ${i}*|grep 'TYPE="swap"'|cut -d : -f 1)
  do
   swpon=$(swapon -s|grep "$j"|cut -d " " -f 1)
#  echo "$j: swpon=$swpon"
   if [ "${swpon:0:8}" == "$j" ]
   then
    bizz=true
   fi
  done
 fi
#read -p "pause in do loop"

#echo $bizz 
 if ! $bizz
 then
  mount -t auto "$i" "$drv"  >/dev/null 2>&1
  if [ $? -eq 0 ]
  then
   if [ "$disk_name_type" == "label" ]
   then
    string2=$(grep -i -e ^default -e label "$drv"/{*,*/*,*/*/*}.cfg 2>/dev/null \
    |sed -e s/.*cfg://|head -n2| tr '\n' '|')
   elif [ "$disk_name_type" == "title" ]
   then
    string2=$(grep -i -e title "$drv"/{*,*/*,*/*/*}.cfg 2>/dev/null|sed -e s/.*cfg://|head -n1)
   elif [ "$disk_name_type" == "version" ]
   then
    string2=$(grep -i version "$drv"/{*,*/*,*/*/*}.cfg 2>/dev/null|sed -e s/.*cfg://|head -n1)
   elif [ "$disk_name_type" == "debian" ]
   then
    string2=$(grep -i -e Architectures -e Origin -e suite -e version \
    "$drv"/dists/*/Release 2>/dev/null|head -n4|sed 's/.*: *//'| tr '\n' ' ')
   elif [ "$disk_name_type" == "mini" ]
   then
    string2=$(grep 'This is an installation system for Ubuntu' \
    "$drv"/f1.txt 2>/dev/null|sed -e s/.*Ubuntu/Ubuntu/)
   elif [ "$disk_name_type" == "desktop" ]
   then
    string2=$(grep DISKNAME "$drv"/README.diskdefines 2>/dev/null|sed -e s/.*DISKNAME\ *//)
   else
    string2="not_$drv"
   fi
  else
   string2="not_$drv"
  fi
  sleep 0.5
  umount "$i" "$drv" 2>/dev/null
  sync
 fi
 if [ "$string2" == "$string1" ]
 then
  echo "$string2 _found_ in $i"
  question="$question and in $i -- automatic identification"
  umount "$i" "$drv" 2>/dev/null
  df -h 2>/dev/null | grep "^$i"
  if [ $? -eq 0 ]
  then
   echo "$i matches the disk-name but could not be unmounted. Is it the live drive?"
  else
   target="$i"
  fi
 fi
done
sync
umount "$drv" >/dev/null 2>&1
rmdir "$drv"
sync

# echo "target: $target"
# exit
}

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

function menu_shell {

# check program packages, offer installation and show a splash screen

check_packages

ans="-1"
defitem="s"

#echo "$version"

btitle="$version - Welcome and Notice about Overwriting"
message=\
"<center><span style='font-size:28px';>Welcome to <b>$version</b></span></center>
\n
<center>Please copy the data you want to keep to another device,\n
for example an external hard disk drive or a cloud service,\n
and double-check that you select the correct target device!\n
\n
<b>mkusb</b> will use the whole target device, so\\n
\n
\Z7*\Zn\Z1 the target will be formatted and completely overwritten\Zn \Z7*\Zn\\n
\n
There will be no easy way to recover any previous data.\n
Expensive intelligence services might restore some data.</center>"

mkz_msg "$message" "--title=$btitle" "--width=$(($wadd+640))" "--height=$(($hadd+400))" "--cancel-label=Continue"
#mkz_msg "$message" "--title=$btitle" "--width=$(($wadd+640))" "--height=$(($hadd+400))" "--cancel-label=About"

##################
#legacy=true
#
#mkz_msg "$message" "--title=$btitle" "--width=$(($wadd+560))" "--height=$(($hadd+400))" "--cancel-label=About"
##################
 
#if [ $? -eq 1 ]
#then
# about
#fi

while [ "$ans" != "q" ]
do
 echo "$separator"
 echo "menu_shell:"
 if test -s "$selected"
 then
  read imagefile < "$selected"
 fi

# if 'not ISO file' and 'not empty string'

 if [ "${imagefile/.iso}" == "$imagefile" ] && [ "$imagefile" != "" ]
 then
  liveonly=true
  livesel="-"
 elif $liveonly
 then
  livesel="Live only selected (toggle live only or persistent live)"
 else
  livesel="Persistent live selected (toggle live only or persistent live)"
 fi

 if test -s "$selected"
 then
  if test -f "$imagefile" || test -b "$imagefile"
  then
   menutitle="Selected: ${imagefile##*/}"
   ans=$(zenity --list --width=$(($wadd+760)) --height=$(($hadd+280)) \
--title="$version - $menutitle" --cancel-label="Exit from mkusb" \
--window-icon="/usr/share/icons/hicolor/48x48/apps/mkusb.png" \
--column="Hotkey" --column="Action for ${imagefile##*/}" \
i "Install ==> find target drive and copy, flash, clone ..." \
s "Select source - iso, img, img.gz or img.xz file" \
l "$livesel" \
w "Wipe menu" \
h "Help menu" \
q "Quit from mkusb" 2>> "$zerrlog")
  else
   imagefile=
   menutitle="Starter menu - No image file selected"
   ans=$(zenity --list --width=$(($wadd+760)) --height=$(($hadd+280)) \
--title="$version - $menutitle" --cancel-label="Exit from mkusb" \
--window-icon="/usr/share/icons/hicolor/48x48/apps/mkusb.png" \
--column="Hotkey" --column="Action" \
s "Select source - iso, img, img.gz or img.xz file" \
l "$livesel" \
w "Wipe menu" \
h "Help menu" \
q "Quit from mkusb" 2>> "$zerrlog")
  fi
 else
  imagefile=
  menutitle="Starter menu - No image file selected"
  ans=$(zenity --list --width=$(($wadd+760)) --height=$(($hadd+280)) \
 --title="$version - $menutitle" --cancel-label="Exit from mkusb" \
--window-icon="/usr/share/icons/hicolor/48x48/apps/mkusb.png" \
--column="Hotkey" --column="Action" \
s "Select source - iso, img, img.gz or img.xz file" \
l "$livesel" \
w "Wipe menu" \
h "Help menu" \
q "Quit from mkusb" 2>> "$zerrlog")
 fi

retval=$?

#echo "retval=$retval"
#echo "ans=$ans"

 if [ $retval -eq 1 ]
 then
  ans=$retval
 fi
 ans=${ans:0:1}          # fix for buggy(?) zenity --list in trusty

#echo "ans=$ans"
#echo "in menu_shell: imagefile=$imagefile"
#echo "ans=xxx${ans}xxx"
#read -p "press enter to continue"
# read -n 1 -s ans

 if [ "$ans" == "s" ]
 then
  select_source_as_user
 elif [ "$ans" == "i" ]
 then
  echo "imagefile=$imagefile"
  persnote_flag=true
  usage_prep_final "$imagefile"
 elif [ "$ans" == "l" ]
 then
  if $liveonly && [ "${imagefile/.iso}" != "$imagefile" ]
  then
   chk4uefi
   if [ $? -eq 0 ]
   then
    liveonly=false
   else
    liveonly=true
   fi
  else
   liveonly=true
  fi
 elif [ "$ans" == "w" ]
 then
  wipe_menu
 elif [ "$ans" == "1" ]
 then
  ans="q"
 elif [ "$ans" == "h" ]
 then
  help_menu
 fi
done
}

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

function wipe_menu {

while [ "$ans" != "q" ]
do

 ans=$(zenity --list --width=$(($wadd+760)) --height=$(($hadd+320)) \
--title="$version - wipe menu (all options wipe the target device)" --cancel-label="Quit" \
--window-icon="/usr/share/icons/hicolor/48x48/apps/mkusb.png" \
--column="Hotkey" --column="Action" \
s "Standard: create MSDOS partition table with FAT32 partition" \
b "Big drive: create GUID partition table with NTFS partition" \
g "General: use 'gparted' to make partition table and partition(s)" \
a "Advanced: create GUID partition table (skeleton for installing an OS)" \
f "wipe the First megabyte (mibibyte)" \
w "wipe the Whole device - consider other options except for special cases" \
q "Quit from this help menu" \
)
# 2>> "$zerrlog")

 retval=$?

echo "retval=$retval"

 if [ $retval -eq 1 ]
 then
  ans=1
 fi
 ans=${ans:0:1}          # fix for buggy(?) zenity --list in trusty

# echo "ans=xxx${ans}xxx"

 makepart=
 if [ "$ans" == "1" ]
 then
  ans="q"
 elif [ "$ans" == "s" ]
 then
  makepart="msdos"
  usage_prep_final "wipe-1"
 elif [ "$ans" == "a" ]
 then
  makepart="gpt_skel"
  usage_prep_final "wipe-1"
 elif [ "$ans" == "b" ]
 then
  makepart="gpt_ntfs"
  usage_prep_final "wipe-1"
 elif [ "$ans" == "g" ]
 then
  makepart="gpart"
  usage_prep_final "wipe-1"
 elif [ "$ans" == "f" ]
 then
  usage_prep_final "wipe-1"
 elif [ "$ans" == "w" ]
 then
  usage_prep_final "wipe-whole-device"
 fi
 sig=$?
 if [ $sig -ne 0 ]
 then
  return $sig
 fi
done
ans=0
}

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

function mk_msdos {

# make an MSDOS partition table and a FAT32 file system

label1=$(zenity --forms --text="
Enter a label (name) for the FAT32 partition
(only the first 11 characters will be used)
" --add-entry="Label" --window-icon="/usr/share/icons/hicolor/48x48/apps/mkusb.png" \
--title="$version - Enter label" 2> /dev/null)

label1="${label1:0:11}"
label1="${label1^^}"
#echo "Label (name) for the FAT32 partition: $label1"

#dd if=/dev/zero of="$target" bs=1024 count=1024 2>&1
parted -s "$target" mklabel msdos
sleep 0.5
parted -s "$target" mkpart primary 1048576b 100%
sleep 0.5
parted -s "$target" set 1 boot on  # set boot flag on partition 1
sleep 0.5
if [ "${target:0:11}" == "/dev/mmcblk" ]
then
 mkfs.vfat -v -F 32 -n "$label1" "${target}p1"
else
 mkfs.vfat -v -F 32 -n "$label1" "${target}1"
fi
if [ $? -eq 0 ]
then
 strut="created MSDOS partition table and FAT file system"
 sync
 sleep 0.5
 sudo blkid -c /dev/null "${target}"* # > /dev/null 2>&1
 sleep 0.5
 sync
 part_info "created MSDOS partition table and FAT file system"
else
 strut="mk_msdos: could not create MSDOS partition table and FAT file system"
 warner "$strut"
fi
/bin/echo -e "$inversvid $strut $resetvid"
}

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

function mk_gpt_skel {

# make a GPT partition table and 
# a partition with a FAT32 file system and a bios_grub partition

#dd if=/dev/zero of="$target" bs=1024 count=1024 2>&1
parted -s "$target" mklabel gpt
sleep 0.5
parted -s "$target" mkpart primary 1048576b 320MB
sleep 0.5
parted -s "$target" set 1 boot on  # set boot flag on partition 1
sleep 0.5
parted -s "$target" mkpart primary 320MB 321MB
sleep 0.5
parted -s "$target" set 2 bios_grub on
sleep 0.5
if [ "${target:0:11}" == "/dev/mmcblk" ]
then
 mkfs.vfat -v -F 32 -n EFI "${target}p1"
else
 mkfs.vfat -v -F 32 -n EFI "${target}1"
fi
sleep 1.0
sync
part_info "created GUID partition table with EFI and bios_grub partitions"
}

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

function mk_gpt_ntfs {

# make a GUID partition table and an NTFS file system

label1=$(zenity --forms --text="
Enter a label (name) for the NTFS partition
" --add-entry="Label" --window-icon="/usr/share/icons/hicolor/48x48/apps/mkusb.png" \
--title="$version - Enter label" 2> /dev/null)

echo "Label (name) for the NTFS partition: $label1"

#dd if=/dev/zero of="$target" bs=1024 count=1024 2>&1
parted -s "$target" mklabel gpt
sleep 0.5
parted -s "$target" mkpart primary 1048576b 100%
sleep 0.5
if [ "${target:0:11}" == "/dev/mmcblk" ]
then
 mkfs.ntfs -v -f -L "$label1" "${target}p1"
else
 mkfs.ntfs -v -f -L "$label1" "${target}1"
fi
sleep 0.5
parted -s "$target" set 1 msftdata on
sleep 0.5
sync
part_info "created GUID partition table with EFI and bios_grub partitions"
}

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

function mk_gpart {

# general method to make a partition table and file system(s)

message="<h2>General method with 'gparted'</h2>

Partition tables: MSDOS is old. GUID (GPT) is new

<h3>Use GPT to install operating systems in UEFI mode</h3>
<h3>and for really big drives, more than 2 TB</h3>

Device -- Create partition table -- Advanced -- Select 'gpt'<br>
<br>
and create at least one partition with a suitable file system.<br>
<br>
If you plan to connect the drive<br>
<br>
- only to linux, use 'ext4'<br>
<br>
- also to Windows, use 'NTFS'<br>
<br>
- also to Mac OS, use 'FAT32', but it is really not good for big partitions.<br>
You may consider making several partitions<br>
<br>
Add a 'label' to make it easy to identify the drive and its partition"

echo "$message" | sed -e 's#</*br>##g' -e 's#</*h[1-3]>##g'

which gparted
if [ $? -eq 0 ]
then
 mkz_msg "$message" \
 "--title=$version - Use 'gparted' to create a partition table" \
 "--width=$(($wadd+640))" "--height=$(($hadd+600))" "--cancel-label='Quit'" &

 gparted "$target"
 part_info "Check the partition table and partitions!"
else
 mess1="Install 'gparted' to make a partition table.<br>
<br>
The only action was that mkusb wiped the first megabyte,"
 mkz_msg "$mess1" \
 "--title=$version - Install 'gparted' to make a partition table" \
 "--width=$(($wadd+640))" "--height=$(($hadd+400))" "--cancel-label='Quit'"

 clean_mtab_n_colors_n_zerrlog
 rm "$zerrlog"
 exit
fi
}

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

function part_info {

LANG="$curlang"
sync
sleep 0.5
blkid -c /dev/null "${target}?" > /dev/null
sleep 0.5
if [ "${target:0:11}" == "/dev/mmcblk" ]
then
 warner "Unplug and re-plug the flash card to see the correct info ..."
fi
partinfo=$(parted -s "$target" print; \
echo " "; \
lsblk -o MODEL,NAME,FSTYPE,LABEL "$target")

echo "$separator
<pre>
$partinfo
</pre>"

zenity --info --text="<tt>$partinfo</tt>" --width=720 \
--title="$version - $1" \
--window-icon="/usr/share/icons/hicolor/48x48/apps/mkusb.png" 2>/dev/null
lang=C
}

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

function use_url {

if [ "$distr" != "opensuse" ]
then

# Run the browser as your regular user (not as superuser)

usrstr=$(who|grep -m1 -e tty7 -e console -e ':0'|cut -d ' ' -f 1)
if [ "$usrstr" == "" ]
then
 echo ""
 echo "mkusb found no regular user ID; does not want to browse the internet"
 echo "automatically with superuser privileges. Please browse manually to"
 echo ""
 echo "$1"
 echo ""
 exit
fi
cmdstr="su $usrstr -c"

if [ -n "$BROWSER" ]; then
  $cmdstr "$BROWSER $1"
elif which gnome-open > /dev/null; then
  $cmdstr "gnome-open $1"
elif which gnome-www-browser > /dev/null; then
  $cmdstr "gnome-www-browser $1"
elif  which xdg-open > /dev/null; then
  $cmdstr "xterm -fa default -fs 12 -e xdg-open $1"
else
  echo "Could not detect a web browser to use"
fi

else

# Browse manually in opensuse

 echo " "
 echo "Open your internet browser and browse manually to"
 echo " "
 echo "$1"
 echo " "
 zenity --info --title="$version - browse manually to" \
--text="$1"
fi
}

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

function help_menu {

while [ "$ans" != "q" ]
do

 ans=$(zenity --list --width=$(($wadd+760)) --height=$(($hadd+330)) \
--title="$version - help menu" --cancel-label="Quit" \
--window-icon="/usr/share/icons/hicolor/48x48/apps/mkusb.png" \
--column="Hotkey" --column="Action" \
h "Help to select drive - advanced help text" \
f "Flow - brief description of work flow" \
m "Manual page - man mkusb" \
w "Wiki page - https://help.ubuntu.com/community/mkusb" \
b "Background colours - tweak the final checkpoint colours" \
t "Tweak zenity window size" \
a "About" \
q "Quit from this help menu" \
 2>> "$zerrlog")

 retval=$?
 if [ $retval -eq 1 ]
 then
  ans=$retval
 fi
 ans=${ans:0:1}          # fix for buggy(?) zenity --list in trusty

# echo "ans=xxx${ans}xxx"

 if [ "$ans" == "1" ]
 then
  ans="q"
 elif [ "$ans" == "f" ]
 then
  work_flow
 elif [ "$ans" == "h" ]
 then
  mkhelp
 elif [ "$ans" == "m" ]
 then
  if test -s /usr/share/man/man8/mkusb.8.gz
  then
   xterm -geometry 90x24 -fa default -fs 10 -bg '#ebeceb' -fg black -T 'man mkusb' -e man mkusb
  else
   zenity --info --text=\
"Install mkusb from the PPA to get the manual page.
See https://help.ubuntu.com/community/mkusb" 2>> "$zerrlog"
  fi
 elif [ "$ans" == "w" ]
 then
  use_url "https://help.ubuntu.com/community/mkusb"
 elif [ "$ans" == "b" ]
 then
  if "$legacy"
  then
   echo "Background colours are not used in legacy mode"
  else
   coledit
  fi
 elif [ "$ans" == "t" ]
 then
  tweak_zws
 elif [ "$ans" == "a" ]
 then
  about  
 fi
done
ans=0
}

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

function select_source_as_user {

LANG="$curlang"

touch "$selected"
chmod ugo+rwx "$selected"
#read imagefile < "$selected"

test -f "$imagefile" || test -b "$imagefile"
if [ $? -eq 0 ]
then
 choice="$imagefile"	
else
 imagefile=""
 choice="$PWD/"
fi

usrstr=$(who|grep -m1 -e tty7 -e console -e ':0'|cut -d ' ' -f 1)

if [ "$distr" == "opensuse" ]
then
 su $usrstr -c "zenity --info --text='test window' --timeout 1 > /dev/null 2>&1"
 isdisplay=$?
#echo "usrstr=$usrstr"
#echo "isdisplay=$isdisplay"
#sleep 3
else
 isdisplay=0
fi
if [ "$usrstr" == "" ] || ! ( [ $isdisplay -eq 0 ] || [ $isdisplay -eq 5 ] )
then
 echo ""
 echo "mkusb found no regular user ID;"
 echo "tries to select source file"
 echo "with root privileges."
 zenity --file-selection --title "$version - Select source file" \
--filename="$choice" --file-filter={*.i[sm][og]*,*.iso,*.img,*.img.?z,s[dr]?,mmc*,*} \
> "$selected" 2>> "$zerrlog"
else
 su $usrstr -c "zenity --file-selection --title \"$version - Select source file\" \
--filename=\"$choice\" --file-filter={*.i[sm][og]*,*.iso,*.img,*.img.?z,s[dr]?,mmcblk?,*} \
> \"$selected\" 2>> \"$zerrlog\""
fi

read imagefile < "$selected"

echo "select_source: imagefile=$imagefile"
#LANG=C
}

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

function file_from_parameter {

 usage_prep_final "$@"
}

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

function grub_n_iso {

# parameters: <source> <target> <result>

#legacy=true

# mkusb_sdir=/usr/share/mkusb

inst=0
bpsiz=128
if [ "${2:0:11}" == "/dev/mmcblk" ]
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'."

probe_source

looper=$(mktemp -d)
targ1=$(mktemp -d)
usbdata=$(mktemp -d)
tailfile=$(mktemp)

if [ "$1" == "-v" ]
then
 echo "mk-grub-n-iso $version"
 exit
fi
parcnt=$#
if [ $parcnt -ne 3 ] || [ "$USER" != "root" ] || [ "$1" == "-h" ]
then
 echo "Try again with the correct target device according to the list below"
 echo ""
 lsblk -o MODEL,NAME,FSTYPE,LABEL,MOUNTPOINT,SIZE /dev/[^f]d?
 exit
fi

# check if running an installed system in UEFI mode, and
# in that case 'upefi' (usb-pack_efi.tar.gz) cannot be used

if ! $biosbl || ! test -f "$mkusb_sdir"/usb-pack_efi.tar.gz
then
 upefi=false
 mess0="The boot system for UEFI must 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 "$srcorig ################"
srclocal="${srcorig##*/}"
#echo "$srclocal ###############"

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

select_boot_system "$looper"

if ! test -f "$looper"/boot/grub/grub.cfg && ! $upefi && ! $biosbl
then
 ng1="'.../boot/grub/grub.cfg': file not found"
 ng2="In an installed system in UEFI mode, mkusb needs
'$looper/boot/grub/grub.cfg'
from the source iso file, but it is not found.

Try with a Debian or Ubuntu family *amd64* iso file."
 echo "$ng1"
 echo "$ng2"
 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 - preparing persistent live drive ..." \
--percentage=0 --auto-close --no-cancel \
--window-icon="/usr/share/icons/hicolor/48x48/apps/mkusb.png"  2>> "/dev/null") & pid=$!

echo "# Start grub_n_iso" > "$tailfile"

sync
sleep 1

for i in $(ps -A|grep -A2 $pid|grep zenity|sed -e 's/^ *//' -e 's/ .*//')
do
 dnward_win "$i" "760" "100"
done

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 -f "$srclocal" && [ "${srclocal/.iso}.iso" == "$srclocal" ]
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

#is_file "$mkusb_sdir"/usb-pack_efi.tar.gz
#if [ $? -ne 0 ]
#then
# clear_grn "$pid" "$looper" "$targ1" "$tailfile" "$usbdata"
# exit
#fi

source="$srcorig"

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

#echo "Unplug and replug the target device, if it is a USB drive" #####################
#ans=""
#while [ "$ans" != "g" ]
#do
# read -p "Confirm with g when ready to go ahead (g) " ans
#done
#
#chk4unplug
#if [ $? -eq 1 ]
#then
# exit
#fi
#
# re-read partition info
#
#blkid -c /dev/null /dev/[^f]d??

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

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

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

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

targsize=$(lsblk -db /dev/[^f]d? /dev/mmcblk?|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

get_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
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
#read -p "checking after mklabel gpt or msdos"

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

if [ "$part_type" == "gpt" ]
then
 # partition 2 - bios_grub
 #parted -s "$2" mkpart primary 1048576b 2097152b
 parted -s "$2" mkpart primary 1MB 2MB
 lsblk -f "$2" > /dev/null
 sleep 0.5
# read -p "checking after mkpart primary 1MB 2MBq"
else
 # partition 2 - extended container for casper-rw
 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

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

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

# partition 5 - ext4 - "casper-rw"

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
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 boot flag on partition 2
fi
parted -s "$2" set 3 boot on  # set boot flag on partition 3
sync
lsblk -f "$2" > /dev/null
sleep 0.5

#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 "30
# make partitions: preparing $part" >> "$tailfile"

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

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 "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|cut -d '/' -f2)
initrd=$(find * -name "initrd*"|grep -e casper -e live|head -n1|cut -d '/' -f2)
cd "$startdir"

#echo "persist=$persist"
#echo "vmlinuz=$vmlinuz"
#echo "initrd=$initrd"
#read -p "Enter to continue 2"

label="${source##*/}"
label="${label/edubuntu/edu}"
label="${label/kubuntu/kub}"
label="${label/lubuntu/lub}"
label="${label/mythbuntu/myb}"
label="${label/ubuntu-desktop-next/unx}"
label="${label/ubuntu-gnome/ugn}"
label="${label/ubuntu-mate/umt}"
label="${label/server-i386/s32}"
label="${label/server-amd64/s64}"
label="${label/ubuntukylin/uky}"
label="${label/ubuntustudio/ust}"
label="${label/xubuntu/xub}"
label="${label/ubuntu/ubu}"
label="${label/ToriOS/tori}"
label="${label/ToriOS_Live/tori}"
label="${label/Debian/deb}"
label="${label/daily}"

label=$(echo "$label"|sed -e s/desktop// -e s/untu// -e s/LTS// -e s/\\.//g \
 -e s/-//g -e s/amd64/-64/ -e s/i386/-32/ -e s/iso//)
if [ "$label" == "" ]
then
 label="${source##*/}"
fi
label="${label//-}"
label="${label//_}"
label="${label// }"
label="${label:0:11}"
dosfslabel "$part" "$label"
if [ "$disk_name_type" == "debian" ] || [ "$disk_name_type" == "torios-debian" ]
then
 tune2fs -L "persistence" -O ^has_journal "${tu}5"
else
 tune2fs -L "${persist}-rw" -O ^has_journal "${tu}5"
fi
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 mkusb 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 mkusb 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)

rm -r "$targ1"/* 2> /dev/null
sync

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

if $biosbl
then
 if $upefi && test -f "$mkusb_sdir"/usb-pack_efi.tar.gz
 then
  /bin/echo -ne "$inversvid UEFI Bootloader: $resetvid "
  grub-install --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
  /bin/echo -e "$inversvid No UEFI Bootloader available $resetvid
mkusb needs the package 'usb-pack-efi' with the file
'usb-pack_efi.tar.gz' from 'ppa:mkusb/ppa' to make a
persistent live system with this iso file boot in UEFI mode.
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
$separator"
 fi
 /bin/echo -ne "$inversvid BIOS Bootloader: $resetvid "
 grub-install --force --removable --no-floppy --boot-directory="$targ1"/boot "$2" 2>&1
fi

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"

sudo rsync -Ha --exclude=filesystem.squashfs "$looper/" "$targ1"
/bin/echo -e "rsync:$inversvid  don't worry, $resetvid symlink errors are *expected*
because of the target file system."

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 mkusb 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 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

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

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

if test -f "$mkusb_sdir"/usb-pack_efi.tar.gz
then
 echo "using usb-pack_efi.tar.gz"
 tar -xvzf "$mkusb_sdir"/usb-pack_efi.tar.gz --directory "$targ1"
 if [ $? -ne 0 ]
 then
  error="- tar: extracting usb-pack_efi"
 fi
fi

# tweak 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

# append the rest of the file (after two first lines)
 
< "$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%${source##*/}%g" \
-e "s/vmlinuz/$vmlinuz/" \
-e "s/casper/$persist/g" \
-e "s/initrd.lz/$initrd/" \
-e '/menuentry/s/"./\U&/' \
>> "$targ1"/boot/grub/grub.cfg

if [ "$disk_name_type" == "debian" ] || [ "$disk_name_type" == "torios-debian" ]
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'

cp "$mkusb_sdir"/backup "$targ1"
cp "$mkusb_sdir"/restore "$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" ]
then
 echo "creating persistence.conf for $disk_name_type"
 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 $chk_upgrd
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 -n | dd of=${tu}4 bs=4096"
# echo "$cmdline"
 do_n_show "$cmdline"
 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
 echo "Maybe too small partition: '$part' or '${tu}4'"
 result="'$error' could not finish"
 btitle="$version - failed installing to $2 :-)"
 echo "$result"
fi

sync
echo "Syncing the target device ..."

# final tasks

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
 if [ "${target:0:11}" == "/dev/mmcblk" ]
 then
  warner "Unplug and re-plug the flash card to see the correct info ..."
 fi
 echo "<pre>"
 echo "parted -s \"$2\" print"
 parted -s "$2" print
 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="$version - Work done with $target :-)"
  echo "$result"
  echo "The target device is ready to use."
  echo "'$srcorig' was installed"
 fi  
else
 btitle="$version - failed unmounting $target :-)"
 result="Could not unmount some partition on the target device. Try manually!"
 echo "$result"
fi
echo "100" >> "$tailfile"
clear_grn "$pid" "$looper" "$targ1" "$tailfile" "$usbdata"
}

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

function probe_source {

looper=$(mktemp -d)
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
 disk_name_type="desktop"
 /bin/echo -e "$inversvid $tmpstr $resetvid"
fi

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=$(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"
  /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" ]
then
 mess1=" You are trying to install an operating system, which is not \n
 developed from Debian or Ubuntu desktop. There may be problems."
 /bin/echo -e "${inversvid}${mess1/\\n}$resetvid"
 is_file "$mkusb_sdir"/maybe-problems.txt
 if [ $? -eq 0 ]
 then
  message=$(cat "$mkusb_sdir"/maybe-problems.txt)
 else 
  message="$mess1"
 fi
 btitle="$version - There may be problems"
 mkz_msg "$message" "--title=$btitle" "--width=$(($wadd+520))" "--height=$(($hadd+480))" "--cancel-label=Quit"
 if [ $? -eq 1 ]
 then
  echo "Zenity error log-file 'zerrlog'=$zerrlog"
  exit
 else
  echo "Good luck :-)"
 fi
else
 chk4ubuntu_upgrades "$tmpstr"
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 checkpoint_question {

mess1=$(lsblk -o MODEL,NAME,FSTYPE,LABEL,SIZE "$target")
message="<b>'<span color='#2252a0'>$source</span>' is identified as the source ISO file</b>

The partition table of a USB drive can be updated by

1: unmounting;  2: unplugging;  3: replugging

<span font='ubuntu mono'>$mess1</span>


<b>Go ahead and overwrite <span color='#2252a0'>$target</span> ?</b>"

zenity --question --text="$message" --title="$btitle" \
--window-icon="/usr/share/icons/hicolor/48x48/apps/mkusb.png" \
--width=760 --height=480 \
--title="$version - Final checkpoint before installing" 2>> "$zerrlog"

if [ $? -eq 1 ]
then
 return 1
fi
}

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

function chk4uefi {

minrel=14.04
mindeb=8

#drels=$(grep DISTRIB_RELEASE /etc/lsb-release|cut -d = -f 2)
#drels=${drels//.}
drels=$(grep VERSION_ID /etc/*release|cut -d \" -f2)
distr=$(grep ^ID= /etc/*release|cut -d = -f2)
if ! ( [ "$distr" == "ubuntu" ] && [ ${drels//.} -ge ${minrel//.} ] \
|| [ "$distr" == "debian" ] && [ ${drels//.} -ge ${mindeb//.} ] )
then
 echo "$separator"
 echo "You are running the following operating system now:"
 cat /etc/lsb-release
 echo "$separator"
 mess1="\Z4$0\Zn\n
\n
might not make all systems bootable in UEFI mode from this version.
You should \Z4work in Debian $mindeb, Ubuntu $minrel or newer\Zn
or a corresponding Ubuntu flavour (Kubuntu, Lubuntu, ... Xubuntu.)"
 echo "$mess1"|sed -e 's/\\Z.//g' -e 's/\\n//g'
 message="$mess1\n
\n
Do you want to continue and maybe get a system only for BIOS mode?
(You can also try using the boot system from the 'ISO file'.)"
 btitle="$version - Make a system only for BIOS mode?"
 mkz_msg "$message" "--title=$btitle" "--width=$(($wadd+600))" "--height=$(($hadd+280))" "--cancel-label=Quit"
 if [ $? -eq 1 ]
 then
  return 1
 else
  echo "$separator"
 fi
fi
}

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

function chk4ubuntu_upgrades {

# parameter $1 is tmpstr from probe_source

ename="$1"

if [ "$disk_name_type" == "desktop" ]
then
 echo "$separator"
 echo -n "chk4ubuntu_upgrades: "
 heads_up="You are installing
\n$ename"
 mess1="\Z4${0##*/}\Zn\n
\n
can set the security upgrade action (the default action of the persistent
\nlive system when security upgrades are available). This method works for
\nUbuntu family operating systems and some 're-spins'. $heads_up
\n\n
This can change 'Download and install automatically' to 'Display immediately'"
 echo "$mess1"|sed -e 's/\\Z.//g' -e 's/\\n//g'
 message="$mess1\n
\n
'Display immediately' is the recommended action for persistent live drives.
\n\n
\Z4Is this what you want?\Zn"
 btitle="$version - Default action for security upgrades"
 mkz_msg "$message" "--title=$btitle" "--width=$(($wadd+560))" "--height=$(($hadd+360))" " \
 --cancel-label=No --ok-label=Yes"
 if [ $? -eq 0 ]
 then
  echo "set security upgrade action to 'Display immediately'"
  chk_upgrd=true
 else
  echo "keep settings"
 fi
#else
# echo "chk4ubuntu_upgrades: keep settings, not an Ubuntu family operating system"
fi
echo "$separator"
}

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

function chk4unplug {

numwily=15.10

drels=$(grep DISTRIB_RELEASE /etc/lsb-release|cut -d = -f 2)
drels=${drels//.}
grep -i ID=.*buntu /etc/*release > /dev/null
if [ $? -ne 0 ] || [ $drels -ge ${numwily//.} ]
then
 echo "$separator"
 echo "You are running the following operating system now:"
 cat /etc/lsb-release
 echo "$separator"
 mess1="Unplug and replug the target device, if it is a USB drive\n
(otherwise old content may remain in the computer's memory)"
 echo "$mess1"|sed -e 's/\\Z.//g' -e 's/\\n//g'
 message="$mess1\n
\n
Do you want to continue now?"
 btitle="$version - Unplug and replug the target device"
 mkz_msg "$message" "--title=$btitle" "--width=$(($wadd+520))" "--height=$(($hadd+280))" "--cancel-label=Quit"
 if [ $? -eq 1 ]
 then
  return 1
 else
  echo "$separator"
 fi
fi
}

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

function center_win {

# parameters "$pid" "$width" "$height"
# static variable icenter used if wmctrl is not installed
#echo "install wmctrl if necessary"

if ! $icenter
then
 return 1
fi

wxh=$(xrandr|grep '*'|sed -e 's/^ *//' -e 's/ .*//')
swide=${wxh/x*}
shigh=${wxh/*x}

zleft=$(( ($swide - $2)/2 ))
if [ $zleft -lt 0 ]
then
 zleft=0
fi
ztop=$(( ($shigh - $3)/2 ))
if [ $ztop -lt 0 ]
then
 ztop=0
fi

which wmctrl > /dev/null
if [ $? -eq 0 ]
then
 wid=
 while [ "$wid" == "" ]
 do
  wid=$(wmctrl -lp | grep $1 | cut "-d " -f1)
 done
 wmctrl -i -r $wid -e 0,$zleft,$ztop,$2,$3
 wmctrl -a $wid
else
 icenter=false
 /bin/echo -e "The window to enter 'percentage for persistence' \
is easier to find if you
$inversvid install wmctrl. $resetvid It needs the 'universe' repository \
in standard Ubuntu."
fi
}

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

function dnward_win {

# displace window half-way up from center
# parameters "$pid" "$width" "$height"
# static variable icenter used if wmctrl is not installed
#echo "install wmctrl if necessary"

if ! $icenter
then
 return 1
fi

wxh=$(xrandr|grep '*'|sed -e 's/^ *//' -e 's/ .*//')
swide=${wxh/x*}
shigh=${wxh/*x}

zleft=$(( ($swide - $2)/2 ))
if [ $zleft -lt 0 ]
then
 zleft=0
fi
ztop=$(( 3*($shigh - $3)/4 ))
if [ $ztop -lt 0 ]
then
 ztop=0
fi

which wmctrl > /dev/null
if [ $? -eq 0 ]
then
 wid=
 while [ "$wid" == "" ]
 do
  wid=$(wmctrl -lp | grep $1 | cut "-d " -f1)
 done
 wmctrl -i -r $wid -e 0,$zleft,$ztop,$2,$3
 wmctrl -a $wid
else
 icenter=false
 /bin/echo -e "The window to enter 'percentage for persistence' \
is easier to find if you
$inversvid install wmctrl. $resetvid It needs the 'universe' repository \
in standard Ubuntu."
fi
}

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

function get_percent {

width=480
height=200

percent=$(mktemp)
perc=0
icenter=true

while [ $perc -lt 1 ] || [ $perc -gt 100 ]
do
 > "$percent"

 zenity --forms --text="
Select the percentage of the remaining drive space for persistence 
The rest is used for storage compatible with Windows
" \
--add-entry="Percentage for persistence (1-100)" \
--window-icon="/usr/share/icons/hicolor/48x48/apps/mkusb.png" \
--title="$version - Select space for persistence" \
  > "$percent" 2> /dev/null & pidf=$!
# > "$percent" 2>> "$zerrlog" & pidf=$!

 center_win "$pidf" "$width" "$height"

 while ! test -s "$percent"
 do
  ps $pidf > /dev/null
  if [ $? -ne 0 ]
  then
   echo "quit" > "$percent"
  fi
  sleep 1
 done

 < "$percent" read perc
 
# echo "after read: perc=$perc"
 if [ "$perc" == "quit" ]
 then
  rm "$percent" 2> /dev/null
  clear_grn "$pid" "$looper" "$targ1" "$tailfile" "$usbdata"
  exit
 fi
 perc=${perc/\%*}
 perc=${perc/\.*}
 echo "$perc"|sed 's/[^0-9]/@/g'|grep @ > /dev/null
 if [ $? -eq 0 ] || [ "$perc" == "" ]
 then
  perc=0
 fi
# echo "after fix: perc=$perc"
 
done

rm "$percent" 2> /dev/null
}

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

function param_general {

#echo Usage: sudo -H $0 [source] [extra]

ctest1=false

if [ $# -eq 0 ]
then
 ctest1=true
 ctest2=true
 return
fi

for j in "${param1[@]}"
do
 if [ "$j" == "$1" ]
 then
#  echo "$j is OK"
  ctest1=true
 fi
done
if $ctest1 || test -f "$1" || test -b "$1" || test -c "$1"
then
 ctest1=true
# echo "parameter1 is OK"
else
 echo "parameter1 is bad"
fi

ctest2=true
k=$#
while [ $k -gt 1 ]
do
 ctestk=false
 for j in "${param2[@]}"
 do
  if [ "$j" == "$2" ]
  then
#   echo "$j is OK"
   ctestk=true
  fi
 done
 if ! $ctestk
 then
  ctest2=false
 fi
 shift
# echo "k=$k"
 k=$(($k-1))
done

if $ctest2
then
echo -n
# echo "parameters 2... (if any) are OK"
else
 echo "some parameters 2... are bad"
fi
}

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

function param_specific {

#echo "dollar=$*"

if [ "${system/img}" != "$system" ]
then
 system="${system%.*}"
fi
#echo "$system"

# print version and usage on demand

if [ "$1" == "-v" ]
then
 echo "$version"
 exit
elif [ "$1" == "-h" ]
then
 mkusb_usage $*
 exit
fi 

# usage text

#if [ "$USER" != "root" ] || [ "$HOME" != "/root" ] || ! $ctest1 || ! $ctest2
if [ "$(whoami)" != "root" ] || [ "$HOME" != "/root" ] || ! $ctest1 || ! $ctest2
then
 if ! $ctest1 || ! $ctest2
 then
  mkusb_usage $*
  exit
 else
  echo "Usage:"
  echo "sudo -H $0 $*"
  exit
 fi
fi
}

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

function par2chk {

# par2chk <param>

j=$1

#echo "par2chk: j=$j"

ctestk=1
k=$#
while [ $k -gt 1 ]
do
  if [ "$j" == "$2" ]
  then
#   echo "$j found"
   ctestk=0
  fi
 shift
# echo "k=$k"
 k=$(($k-1))
done

if [ $ctestk -eq 0 ]
then
 echo "par2chk: $j is found"
else
echo -n
# echo "$j is not found"
fi
return $ctestk
}

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

function check_file {

# check usage mode and input file extension

source="$1"
srcorig="$1"
system="${1%.*}"

if [ "$1" == "" ]
then
 echo "No input file specified yet"
elif   [ "${1/.iso}.iso" != "$1" ] && \
     [ "${1/.img}.img" != "$1" ] && \
     [ "${1/.img.gz}.img.gz" != "$1" ] && \
     [ "${1/.img.xz}.img.xz" != "$1" ]
then
 if [ "$1" == "wipe-whole-device" ] || [ "$1" == "/dev/zero" ]
 then
  echo "Wipe the whole device ... :"
  source="/dev/zero"
 elif [ "$1" == "wipe-1" ] || [ "$1" == "wipe1" ]
 then
  echo "Wipe the first megabyte (MibiByte) ... :"
  source="/dev/zero"
  cnt="count=$count"
 elif [ "$1" == "wipe" ] || [ "$1" == "wipe-menu" ]
 then
  echo "Wipe menu ... :"
  check_packages
  wipe_menu
  clean_mtab_n_colors_n_zerrlog
  rm "$zerrlog"
  exit
 elif [ "${1%/*}" == "/dev" ]
 then
  echo "Clone a device ... :"
 else
  badfil1="Bad choice of source file"
  badfil2="'$1' is neither an iso file, img file nor an img.{gz,xz} file :-(

Tip: There should be an extension, and the extension
should be written with lower-case letters,
'File.iso' or 'file.img' or 'File.img.gz' or 'file.img.xz'"
  echo "$badfil2"
  warner "$badfil1" "$badfil2"
  ans=0
  return 1
 fi
elif [ ! -f "$source" ]
then
 echo ":-( $source is not found :-("
# double quotes makes source file name work with some special characters
 echo "Try quotes around the file name"
 echo "sudo -H path/mkusb \"$source\""
 return 1
fi
if [ "$source" == "/dev/zero" ]
then
 liveonly=true
fi
if [ "${1/.iso}.iso" != "$1" ]  # true for non-iso files
then
 if ! $liveonly
 then
  echo "The source is not an ISO file. $0"
  echo "will not try make a persistent live system."
  liveonly=true
 fi
fi
}

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

function asker {

# asker <question>

zenity --question --text="$1" \
--width=$(($wadd+760)) --height=$(($hadd+300)) \
--title="$version - $1" \
--window-icon="/usr/share/icons/hicolor/48x48/apps/mkusb.png" 2>/dev/null

if [ $? -ne 0 ]
then
 return 1
fi
}

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

function warner {

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

if [ $# -eq 1 ]
then
 message="$1"
else
 message="$2"
fi
zenity --warning --text="$message" \
--width=$(($wadd+760)) --height=$(($hadd+300)) \
--title="$version - $1" \
--window-icon="/usr/share/icons/hicolor/48x48/apps/mkusb.png" 2>/dev/null
}

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

function do_n_show {

#do_n_show <cmdline>

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

echo "$separator"
echo "do_n_show:"
echo "$cmdtext"
echo " "
cmdfile=$(mktemp)
tmpfile=$(mktemp)

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 ..."

bash $cmdfile |tee "$tmpfile" |sed -u 's/^100$/99/'|sed -u 's/Done/100/' | \
zenity --progress --title="$version - progress ..." \
--text="$cmdtext

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

sync
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="<tt>
$ans1</tt>" \
--title="$version - error message" \
--window-icon="/usr/share/icons/hicolor/48x48/apps/mkusb.png" 2>> "$zerrlog"
 return 1
else
 echo "do_n_show: Work done"
 echo "$separator"
fi
}

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

function clear_grn {

# clear_grn "$pid" "$tailfile" ($* catches files and directories)

#echo "clear_grn: pid=$1"
#ps -A|grep -A4 $1|grep -e tail -e zenity|sed 's/^ *//'

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 $*

#echo "clear_grn: parameters: $*"
#echo 'clear_grn: ls -ltr /tmp/tmp.*'
clean_mtab_n_colors_n_zerrlog
#rm "$zerrlog"
echo "Zenity error log-file 'zerrlog'=$zerrlog"
}

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

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" ]
 then
  menu_package_installer needs grub-install "needed in order to install 'persistent live'." grub-pc
 else
  biosbl=false
  echo "$separator"
  message="mkusb cannot install 'grub-pc' in installed systems in UEFI mode.
'grub-pc' is is used to make persistent live drives bootable in BIOS mode.

You *can* install 'grub-pc' in all live systems, so if you want a persistent
live system, that can boot in BIOS mode, you should run mkusb in BIOS mode
or in a live or persistent live session in UEFI mode."
  echo "$message"
  echo "$separator"
  warner "cannot install 'grub-pc'" "$message"
 fi
else
 menu_package_installer needs grub-install "needed in order to install 'persistent live'." grub-pc
fi
}

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

function get_usb_pack_efi {

if ! test -f /usr/share/mkusb/usb-pack_efi.tar.gz && 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="mkusb 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)

rm -f "$2"
old_IFS=$IFS  # save the field separator           
IFS=$'\n'     # new field separator, the end of line
first=true           
store=false

echo "set timeout=10" >> "$2"
echo "set default=0" >> "$2"

for line in $(cat "$1")
do
 if [ "${line/menuentry}" != "$line" ] && $first
 then
  storage="$line"
  line="${line/Try/Run}"
  line="${line/ without installing}"
  line="${line%\"*}"
  linp="${line} - persistent live\" {"
  echo "$linp" >> "$2"
  linr="${line} - persistent live to RAM\" {"
  echo "$linr" >> "$toram"
  store=true
 elif [ "$line" == "}" ] && $store
 then
  echo "$line" >> "$2"
  echo "$line" >> "$toram"
  storage="$storage
$line"
#  echo "$storage" >> "toram"
  cat "$toram" >> "$2"
  echo "$storage" >> "$2"
  store=false
  first=false
 elif $store
 then
  echo "${line/--/persistent --}" >> "$2"
  echo "${line/--/toram persistent --}"  >> "$toram"
  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 "$toram"
}

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

function select_boot_system {

# parameter looper

ans=
#find "$looper" -name "*amd64*" | grep -a grub
find "$looper" -name "*amd64*" | grep -a grub > /dev/null 2> /dev/null
#ans=$?
#echo "find "$looper" -name *amd64* | grep -a grub 2>&1 /dev/null"
#echo "select_boot_system: ans=dollarfråga=$ans"
#if [ $ans -eq 0 ] && test -f "$mkusb_sdir"/usb-pack_efi.tar.gz
if [ $? -eq 0 ] && test -f "$mkusb_sdir"/usb-pack_efi.tar.gz
then
 while [ "$ans" != "u" ] && [ "$ans" != "i" ] && [ "$ans" != "q" ]
 do

  ans=$(zenity --list --width=$(($wadd+540)) --height=$(($hadd+240)) \
--title="$version - select boot system" --cancel-label="Quit" \
--window-icon="/usr/share/icons/hicolor/48x48/apps/mkusb.png" \
--text="Select preferred boot system from 'usb-pack_efi' or from 'ISO file'
'usb-pack_efi': does not work with secure boot
'ISO file': does not work with i386 iso files (32-bit systems)" \
--column="Hotkey" --column="Selection" \
i "ISO file" \
u "usb-pack_efi" \
q "Quit from this menu (default 'ISO file' if possible)" \
 2>> "$zerrlog")

  retval=$?
  if [ $retval -eq 1 ]
  then
   ans=$retval
  fi
  ans=${ans:0:1}          # fix for buggy(?) zenity --list in trusty

# echo "ans=xxx${ans}xxx"

  upefi=false
  if [ "$ans" == "1" ]
  then
   ans="q"
  elif [ "$ans" == "u" ]
  then
   upefi=true
  elif [ "$ans" == "i" ]
  then
   upefi=false
  fi
 done
 ans=0

else
 find "$looper" -name "*amd64*" | grep grub > /dev/null 2> /dev/null
 if [ $? -eq 0 ]
 then
  upefi=false
 else
  upefi=true
 fi
fi
echo "select_boot_system: [if installed, use] usb-pack_efi=$upefi"
}

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

function select_partition_table {

while [ "$ans" != "g" ] && [ "$ans" != "m" ] && [ "$ans" != "q" ]
do

 ans=$(zenity --list --width=$(($wadd+540)) --height=$(($hadd+240)) \
--title="$version - select partition table" --cancel-label="Quit" \
--window-icon="/usr/share/icons/hicolor/48x48/apps/mkusb.png" \
--text="Select partition table
GPT - for most computers, can manage huge drives,
MSDOS - can boot many HP computers" \
--column="Hotkey" --column="Selection" \
g "GPT" \
m "MSDOS" \
q "Quit from this menu (default GPT)" \
 2>> "$zerrlog")

 retval=$?
 if [ $retval -eq 1 ]
 then
  ans=$retval
 fi
 ans=${ans:0:1}          # fix for buggy(?) zenity --list in trusty

# echo "ans=xxx${ans}xxx"

 if [ "$ans" == "1" ]
 then
  ans="q"
 fi
 if [ "$ans" == "m" ]
 then
  part_type=msdos
 else
  part_type=gpt
 fi
done
ans=0
}
########################################################################
########################################################################

function gpt_fix {

# $1 is the target device

echo \
"v
q" \
| gdisk "$1" 2>/dev/null |grep -e 'GPT: damaged' > /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
fi
}

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

function gpt_zap {

# $1 is the target device

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

echo "gpt_zap: done"
}

########################################################################
########################################################################
#
# mkusb main program
#
########################################################################
########################################################################

#echo "\$1=$1"
#echo "\$#=$#"
#/bin/echo -en "$resetvid"

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

# check if all drives should be available at start (not only USB)
# usbonly default true, can be changed with parameter2 'all'

if par2chk all "$@" || par2chk anh "$@"
then
 usbonly=false
else
 usbonly=true
fi
echo "main: usbonly=$usbonly" ##########

if par2chk p "$@" || par2chk -p "$@" || par2chk persistent "$@"
then
 liveonly=false
 persnote_flag=true
else
 liveonly=true
fi
echo "main: liveonly=$liveonly" ##########

check_file "$1"
if [ $? -eq 0 ]
then
 echo "main: source='$source'" ##########
else
 exit
fi

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

if [ $# -eq 0 ]
then
 menu_shell
else
 file_from_parameter "$@"
fi
clean_mtab_n_colors_n_zerrlog
rm "$zerrlog"
stoptim=$(date '+%s')
usedtim=$(($stoptim - $starttim))
timestr=$(date -u --date=@$usedtim '+%H:%M:%S')
echo "$separator
Total time used [by mkusb] = $usedtim s; $timestr"

