#!/bin/bash

# ==============================================================================
# wasta-remastersys: script to make an installable livecd/dvd from a
#   customized Ubuntu-based system
#
#
# Originally created by Tony "Fragadelic" Brijeski
# Copyright 2007-2012 Tony "Fragadelic" Brijeski <tb6517@yahoo.com>
#
# Most recently forked from PinguyBuilder which contained EFI bootcode.
# Includes most code changes found in the forks Respin and Bodhibuilder
#
# This version was tested on variants of Ubuntu's Precise 12.04 and up
#   - confirmed on Cinnamon Mint Maya 13  (based on 12.04)
#   - confirmed on Cinnamon Mint 17.x,    Trusty 14.04
#   - confirmed on                        Xenial 16.04
#   - confirmed on                        Bionic 18.04
#
# 2017-06-10 rik: cleaned up apt-setup to ensure the livecd local packages
#   are available offline install (needed for offline uefi installation)
#   - Offline Packages.gz was empty, correcting syntax to properly generate.
# 2018-08-31 rik: setting GRUB_TIMEOUT_STYLE=hidden rather than using older
#   method of setting GRUB_HIDDEN_TIMEOUT
#   - add dkms to local repo downloads: needed to install bcmwl-kernel-source
#   when offline.
# 2018-09-27 rik: for Ubuntu 18.04 based distros, 2 fixes are required:
#   1. /etc/default/grub GRUB_DISTRIBUTOR must have Ubuntu as the FIRST WORD.
#      It seems that Ubuntu's grub is keying off of this word in order to
#      create a /boot/efi/EFI/<word> folder. But at the same time, there is
#      some hard-coded place in Ubuntu's grub that will only look at the
#      /boot/efi/EFI/ubuntu folder when booting in EFI mode.
#   2. After being identified as "Ubuntu", ubiquity will always attempt to
#      run an apt_clone_restore function on a clean install which fails
#      since nothing to restore. Other sources indicate that Ubuntu will be
#      disabling this apt_clone_restore function because it has proven
#      unreliable. So will disable here for all ISOs created with
#      wasta-remastersys.
# 2019-03-11 rik: patching os-prober file so that update-grub will *not*
#   attempt to install grub to the cdrom "optical disc" used for offline
#   installs when in the live system (casper / ubiquity)
# 2019-03-13 rik: ensuring mokutil is installed for secureboot compatiblity
# 2019-04-02 rik: patching partman so drive containing /cdrom won't be
#   considered for install location
#
# ==============================================================================

# checking to make sure script is running with root privileges
if [ "$(whoami)" != "root" ]; then
    echo "Need to be root or run with sudo. Exiting."
    exit 1
fi

BRANDING="wasta-remastersys"
BRAND_NAME="${BRANDING}"
BRAND_BIN="${BRANDING}"
BRAND_ETC="${BRANDING}"
BRAND_INIT="${BRANDING}"
BRAND_LOG="${BRANDING}.log"

if [ ! -d "/etc/$BRAND_ETC" ]; then
    echo "ERROR: the directory /etc/$BRAND_ETC does not exist.  Exiting..."
    exit 1
fi
. /etc/"${BRAND_ETC}"/"${BRAND_NAME}.version"

# Variables
ARCH=$(archdetect | awk -F "/" '{print $1}')

# load the ${BRAND_NAME}.conf file
. /etc/"${BRAND_ETC}"/"${BRAND_NAME}.conf"

# if ${BRAND_NAME}.conf file is incorrect or missing, ensure valid values

if [ "$LIVEUSER" == "" ]; then
    #Somebody must have removed the username from the configuration file
    LIVEUSER="custom"
fi
#make sure live user is all lowercase
LIVEUSER=${LIVEUSER,,}


if [ "$BASEWORKDIR" == "" ]; then
    BASEWORKDIR=/home/"${BRAND_NAME}"
fi
#replace spaces with an underscore
WORKDIR=$(echo ${BASEWORKDIR}/${BRAND_NAME} | sed -e 's/\\ /_/g' -e 's/ /_/g')

if [ ! -d $WORKDIR ]; then
    mkdir -p $WORKDIR
fi

if [ -f $WORKDIR/"${BRAND_LOG}" ]; then
    rm -f $WORKDIR/"${BRAND_LOG}" &> /dev/null
fi

touch $WORKDIR/"${BRAND_LOG}"

#added log_msg to reduce size. code provided by Ivailo (a.k.a. SmiL3y)
log_msg() {
    echo "$1"
    echo "$1" >>$WORKDIR/"${BRAND_LOG}"
}

if [ "$LIVECDLABEL" == "" ]; then
    LIVECDLABEL="Custom-Live-CD"
fi

CDBOOTTYPE="ISOLINUX"

if [ "$SQUASHFSOPTS" == "" ]; then
    SQUASHFSOPTS="-no-recovery -always-use-fragments -b 1M -comp xz"
fi

if ! [ "$BACKUPSHOWINSTALL" == "0" -o "$BACKUPSHOWINSTALL" == "1" ]; then
    BACKUPSHOWINSTALL="1"
fi

#create ${BRAND_INIT}-firstboot script if it doesn't exist and populate with at
#   least removal of the ubiquity*.desktop file from users Desktop and fix for
#   recovery mode
fbtest=""
[ -f /etc/init.d/"${BRAND_INIT}-firstboot" ] &&
    fbtest=$(grep "#REM4560" /etc/init.d/"${BRAND_INIT}-firstboot")

if [ "$fbtest" == "" ]; then
    cat > /etc/init.d/"${BRAND_INIT}-firstboot" <<FOO
#! /bin/bash
### BEGIN INIT INFO
# Provides:          ${BRAND_INIT}-firstboot
# Required-Start:    \$remote_fs \$syslog \$all
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Run firstboot cleanup and fixup items for ${BRAND_NAME} after a remastered system has been installed
### END INIT INFO

PATH=/sbin:/usr/sbin:/bin:/usr/bin:/usr/local/bin:/usr/local/sbin

. /lib/init/vars.sh
. /lib/lsb/init-functions

do_start() {
    #REM4560
    if [ "\$(cat /proc/cmdline | grep casper)" == "" ]; then
        [ "\$VERBOSE" != no ] && log_begin_msg "Running ${BRAND_INIT}-firstboot"
        (sleep 60 && update-rc.d -f ${BRAND_INIT}-firstboot remove) &
        sed -i -e 's/root:x:/root:!:/g' /etc/shadow
        apt-get remove -q -y ubiquity &> /dev/null
        rm -rf /home/*/Desktop/ubiquity*.desktop

        # NeoRouter: clear config
        rm -f /usr/local/ZebraNetworkSystems/NeoRouter/Client.xml &> /dev/null
        # TeamViewer: clear config (added by PinguyBuilder)
        rm -f /opt/teamviewer/config/global.conf &> /dev/null
        #boot-repair: only removed if added by ${BRAND_BIN}.
        apt-get remove -y -q boot-repair &> /dev/null
        #chntpw: only removed if added by ${BRAND_BIN}.
        apt-get remove -y -q chntpw &> /dev/null
        #recreate SSH keys
        dpkg-reconfigure openssh-server &> /dev/null
        #ensure all required 'at' files exist with proper file permission
        dpkg-reconfigure at &> /dev/null
        # ***rik: clear any existing cdrom sources (leftover from livecd install)
        sed -i '\@cdrom:@d' /etc/apt/sources.list &> /dev/null

        #Place your custom commands below this line

        #Place your custom commands above this line

        ES=\$?
        [ "\$VERBOSE" != no ] && log_end_msg \$ES
        apt-get autoremove -y -q &> /dev/null
        return \$ES
    else
        #17.10+ support: mark ubiquity.desktop as trusted executable.
        if [ $(which gio) ]; then
          su $LIVEUSER -c 'gio set "/home/$LIVEUSER/Desktop/ubiquity.desktop" metadata::trusted true'
        fi
    fi
}

case "\$1" in
    start)
        do_start
        ;;
    restart|reload|force-reload)
        echo "Error: argument '\$1' not supported" >&2
        exit 3
        ;;
    stop)
        ;;
    *)
        echo "Usage: \$0 start|stop" >&2
        exit 3
        ;;
esac

FOO

fi

case $2 in
    iso )
        log_msg "Creating the iso file only"
    ;;
    cdfs )
        log_msg "Creating the cd filesystem only"
    ;;
    "" )
        echo " "
    ;;
    * )
        CUSTOMISO="$2"
    ;;
esac

if [ "$3" != "" ]; then
    CUSTOMISO="$3"
fi

if [ "$CUSTOMISO" == "" ]; then
    CUSTOMISO="custom$1.iso"
fi

#replace spaces with an underscore
CUSTOMISO=$(echo $CUSTOMISO | sed -e 's/\\ /_/g' -e 's/ /_/g')

case $1  in

    backup)
        SESSION_TYPE=$(loginctl show-session $(loginctl | grep ${SUDO_USER:-$USER} | awk '{print $1}') -p Type)
        log_msg "System Backup Mode Selected on Session $SESSION_TYPE"
        if [ "$SESSION_TYPE" == "Type=wayland" ]; then
          read -p "
Wayland messes up the ubiquity installer.
This requires research which we probably won't be doing soon.
Press any key to continue and help design a fix...  " KEYSTROKE
        fi
        ;;

    clean)
        echo "Removing the build directory now..."
        rm -rf $WORKDIR
        echo "Done...Exiting"
        exit 0
        ;;

    dist)
        log_msg "Distribution Mode Selected"
        ;;

    *)
        echo "Usage of ${BRAND_BIN} ${BRAND_VERSION} is as follows:"
        echo " "
        echo "   sudo ${BRAND_BIN} backup|clean|dist [cdfs|iso] [filename.iso]"
        echo " "
        echo " "
        echo "Examples:"
        echo " "
        echo "   sudo ${BRAND_BIN} backup"
        echo "        (to make a livecd/dvd backup of your system)"
        echo " "
        echo "   sudo ${BRAND_BIN} backup custom.iso"
        echo "        (to make a livecd/dvd backup iso named custom.iso)"
        echo " "
        echo "   sudo ${BRAND_BIN} clean"
        echo "        (to clean up temporary files of ${BRAND_NAME})"
        echo " "
        echo "   sudo ${BRAND_BIN} dist"
        echo "        (to make a distributable livecd/dvd of your system)"
        echo " "
        echo "   sudo ${BRAND_BIN} dist cdfs"
        echo "        (to make a distributable livecd/dvd filesystem only)"
        echo " "
        echo "   sudo ${BRAND_BIN} dist iso custom.iso"
        echo "        (to make a distributable iso named custom.iso but only"
        echo "         if the cdfs is already present)"
        echo " "
        echo "   cdfs and iso options should only be used if you wish to modify something"
        echo "   on the cd before the iso is created.  An example of this would be to"
        echo "   modify the isolinux portion of the livecd/dvd"
        echo " "
        exit 1
        ;;

esac

cdfs (){
    echo && echo
    log_msg "Enabling ${BRAND_INIT}-firstboot"
    chmod 755 /etc/init.d/"${BRAND_INIT}-firstboot"
    update-rc.d "${BRAND_INIT}-firstboot" defaults

    log_msg "Checking filesystem type of the Working Folder"
    DIRTYPE=$(df -T -P $WORKDIR | grep "^\/dev" | awk '{print $2}')
    log_msg "$WORKDIR is on a $DIRTYPE filesystem"

    #removing popularity-contest as it causes problems with ubiquity installer
    log_msg "Making sure popularity contest is not installed"
    apt-get -y -q remove popularity-contest &> /dev/null

    #removing syslinux-themes as it causes problems
    log_msg "Making sure syslinux-themes is not installed"
    apt-get -y -q purge syslinux-themes* &> /dev/null

    if [ -n "$SLIDESHOW" ]; then
        echo "installing the user selected slideshow $SLIDESHOW"
        apt-get -y -q install ubiquity-slideshow-$SLIDESHOW --quiet --quiet
    fi

    # check whether system is gnome or kde based to load the correct frontend

    if [ "$(ps axf | grep startkde | grep -v grep)" != "" -o "$(ps axf | grep kwin | grep -v grep)" != "" ]; then
        log_msg "Installing the Ubiquity KDE frontend"
        apt-get -y -q install ubiquity-frontend-kde &> /dev/null
        apt-get -y -q remove ubiquity-frontend-gtk &> /dev/null
    else
        log_msg "Installing the Ubiquity GTK frontend"
        apt-get -y -q install --quiet ubiquity-frontend-gtk &> /dev/null
        apt-get -y -q remove ubiquity-frontend-kde &> /dev/null
        until [ -e /usr/lib/ubiquity/ubiquity/frontend/gtk_ui.py ]; do
            log_msg "reattempting to install ubiquity-frontend-gtk..."
            sleep 2
            apt-get update  &> /dev/null
            apt-get -y -q install ubiquity-frontend-gtk &> /dev/null
        done
    fi

    #rik: disable apt_clone_restore function: is not reliable and is wrongly
    #   triggered by other patch to make sure that GRUB_DISTRIBUTOR first word
    #   is 'Ubuntu' in order to ensure EFI installs will boot properly.
    sed -i '\@#wasta:@d' /usr/share/ubiquity/plugininstall.py
    sed -i -e 's@\(def apt_clone_restore(self).*\)@\1\n        return #wasta: apt_clone_restore process is unreliable@' \
        /usr/share/ubiquity/plugininstall.py

    #rik: ensure os-prober ignores 'optical media' (iso9660) partitions
    #   or else for UEFI installs during install update-grub will return an
    #   error saying that grub can't be installed in the cdrom (18.04, 19.10)
    PATCH_FILE=/etc/"${BRAND_ETC}"/patch/50mounted-tests-iso9660.patch
    patch --dry-run -Nu -r - /usr/lib/os-probes/50mounted-tests -i $PATCH_FILE &> /dev/null
    if [[ $? == 0 ]]; then
      log_msg "*** patching os-prober so update-grub will not return error during install"
      patch -Nu -r - /usr/lib/os-probes/50mounted-tests -i $PATCH_FILE
    else
      log_msg "--- WARNING: skipping os-prober iso9660 failed patch. Check if new patch needed."
    fi

    #rik: ensure partman doesn't consider any partitions on the /cdrom device
    #   or else a large USB used for installing will have a large freespace
    #   on it that will make ubiquity consider it for installing to and the
    #   live usb will be corrupted (18.04)
    PATCH_FILE=/etc/"${BRAND_ETC}"/patch/30parted-remove-cdrom-device.patch
    patch  --dry-run -Nu -r - /lib/partman/init.d/30parted -i $PATCH_FILE &> /dev/null
    if [[ $? == 0 ]]; then
      log_msg "*** patching partman so drive containing /cdrom won't be considered"
      patch -Nu -r - /lib/partman/init.d/30parted -i $PATCH_FILE
    #else
      #jcl: seems like this is fixed in 19.10 (from a code read), so keeping silent
    fi

    #Installing isolinux if needed
    log_msg "Making sure isolinux is installed"
    apt-get -y -q install isolinux syslinux-utils &> /dev/null

    #rik: mokutil needs to be installed for grub-efi-amd64-signed to
    #   install correctly during ubiquity install if installing with
    #   secureboot enabled. No apparent negative if kept installed so
    #   won't attempt to remove on legacy install
    #NOTE: a patch to plugininstall.py or install.py was attempted to make
    #   sure mokutil was installed before grub-efi-amd64-signed was installed
    #   as part of ubiquity but I couldn't get this to work for now.
    log_msg "Making sure mokutil is installed for secureboot compatibility"
    apt-get -y -q install mokutil &> /dev/null

    #Installing boot-repair if not already installed
    if [ -x /usr/bin/boot-repair ];
    then
        REMOVE_BOOT_REPAIR=""
        #do not remove on firstboot if already installed
        sed -i \
            -e '\|apt-get .*remove.* boot-repair |d' \
          /etc/init.d/"${BRAND_INIT}-firstboot"
    else
        log_msg "Adding Boot-Repair to LiveCD"
        REMOVE_BOOT_REPAIR=YES
        apt-get -y -q install boot-repair &> /dev/null
#Commenting this section out because the user should not be prompted in
#the middle of remastersys, and shouldn't add PPAs automatically.
#boot-repair will silently fail to install if the package hasn't been made
#available from some trusted source.
#        KEYPRESS=Y
#        until [ -x /usr/bin/boot-repair ] || [ "${KEYPRESS^^}" == "N" ]; do
#            read -p "Add boot-repair PPA for LiveCD?  (Y/n)  "  KEYPRESS
#            if [ "${KEYPRESS^^}" != "N" ]; then
#                add-apt-repository --yes ppa:yannubuntu/boot-repair
#                apt-get update
#                apt-get --quiet install --yes boot-repair
#                add-apt-repository --remove --yes ppa:yannubuntu/boot-repair
#                #Mint's hack of add-apt-repository doesn't support --remove
#                if [[ $? != 0 ]]; then
#                    log_msg "NOTICE: boot-repair PPA forcibly removed."
#                    rm -f /etc/apt/sources.list.d/yannubuntu-boot-repair-*.list
#                fi
#            fi
#        done
    fi

    #Installing chntpw if not already installed
    if [ -x /usr/sbin/chntpw ];
    then
        REMOVE_CHNTPW=""
        #do not remove on firstboot if already installed
        sed -i \
            -e '\|apt-get .*remove.* chntpw |d' \
          /etc/init.d/"${BRAND_INIT}-firstboot"
    else
        log_msg "Adding CHNTPW to LiveCD"
        REMOVE_CHNTPW=YES
        apt-get -y -q install chntpw &> /dev/null
    fi

    log_msg "General space-saving clean-up of THIS COMPUTER before building"
    log_msg "  Remove all old kernels" #(borrowed from PinguyBuilder 4.3.8)
    dpkg -l 'linux-'{image,headers}'-[0-9]*' | sed '/^ii/!d;/'"$(uname -r | sed "s/\(.*\)-\([^0-9]\+\)/\1/")"'/d;s/^[^ ]* [^ ]* \([^ ]*\).*/\1/;/[0-9]/!d' | xargs apt-get -y purge
    echo && echo
    log_msg "  Remove all orphaned packages (autoremove)"
    apt-get -y -q autoremove

    # Check using lightdm and if it is setup properly for a live default session
    if [ "$(grep lightdm /etc/X11/default-display-manager)" != "" ]; then
        if [ -f /etc/lightdm/lightdm.conf ]; then
            AUTOLOGIN=$(grep -s '^autologin-user=' /etc/lightdm/lightdm.conf | awk -F= '{print $2}')
            if [ "${AUTOLOGIN}" ] && [ "${AUTOLOGIN}" != "${LIVEUSER}" ]; then
              echo && echo
              log_msg "WARNING: LIVEUSER already defined in /etc/lightdm/lightdm.conf."
              log_msg "         No autologin until ${LIVEUSER} == ${AUTOLOGIN}"
              echo && echo
            fi
        #JCL: removing - no idea why this is here.  Shouldn't have any impact on
        #     live session, and lots of distributions have their own .desktop.
        #else
        #    if [ ! -f /usr/share/xsessions/ubuntu.desktop ] \
        #    && [ ! -f /usr/share/xsessions/enlightenment.desktop ]; then
        #        log_msg "Lightdm not setup properly. You must set your default desktop with lightdm prior to remastering"
        #        exit 1
        #    fi
        fi
    fi

    # prevent the installer from changing the apt sources.list
    if [ ! -f "/usr/share/ubiquity/apt-setup.save" ]; then
        cp /usr/share/ubiquity/apt-setup /usr/share/ubiquity/apt-setup.save
    fi

    cat > /usr/share/ubiquity/apt-setup <<FOO
#!/bin/bash

# ${BRAND_NAME} custom apt-setup
# we don't run /usr/lib/ubiquity/apt-setup scripts
# instead just use source system sources.list

# original apt-setup saved to apt-setup.save

mkdir -p /target/boot/efi
if [ "${ARCH}" == "amd64" ]; then
    echo "fs0:\EFI\ubuntu\grubx64.efi" > /target/boot/efi/startup.nsh
else
    echo "fs0:\EFI\ubuntu\grubia32.efi" > /target/boot/efi/startup.nsh
fi
rm -f /target/etc/gdm/custom.conf
rm -f /target/etc/mdm/mdm.conf
# ***rik: DONT remove cdrom or else can't install efi packages
# sed -i '\@cdrom:@d' /target/etc/apt/sources.list
# ***rik: livecd cdrom entry created by casper/ubiquity on livecd boot.
#  However, livecd cdrom entry removed by ubiquity in /target so need to
#  ensure all relevant files forcibly copied over to make the cdrom packages
#  (grub-efi, shim, etc.) available for offline install on the target system.
#  The wasta-remastersys-firstboot script will later clean up.
cp /etc/apt/sources.list /target/etc/apt/sources.list
rsync -av /var/lib/apt/ /target/var/lib/apt/
sleep 2
exit 0
FOO
    chmod 755 /usr/share/ubiquity/apt-setup

    sleep 1

    # Step 3 - Create the CD tree in $WORKDIR/ISOTMP
    log_msg "Checking if the $WORKDIR folder has been created"
    if [ -d $WORKDIR/dummysys ]; then
        rm -rf $WORKDIR/dummysys/var/*
        rm -rf $WORKDIR/dummysys/etc/*
        rm -rf $WORKDIR/dummysys/run/*
        rm -rf $WORKDIR/ISOTMP/{isolinux,grub,.disk}
    else
        log_msg "Creating $WORKDIR folder tree"
        mkdir -p $WORKDIR/ISOTMP/{casper,preseed}
        # ***rik: creating media only, not media/cdrom or else symlink
        #         creation by casper on livecd boot won't work
        mkdir -p $WORKDIR/dummysys/{dev,etc,proc,tmp,sys,mnt,media,var}
        if [ -d /run ]; then
            mkdir -p $WORKDIR/dummysys/run
        fi
        chmod ug+rwx,o+rwt $WORKDIR/dummysys/tmp
    fi

    log_msg "Creating $WORKDIR/ISOTMP folder tree"
    mkdir -p $WORKDIR/ISOTMP/{isolinux,install,.disk}

    log_msg "Copying /var and /etc to temp area and excluding extra files  ... this will take a while so be patient"

    if [ "$EXCLUDES" != "" ]; then
        for addvar in $EXCLUDES ; do
            VAREXCLUDES="$VAREXCLUDES --exclude='$addvar' "
        done
    fi

    rsync --exclude='*.log.*' --exclude='*~' --exclude='*.pid' --exclude='*.bak' --exclude='*.[0-9].gz' --exclude='*.deb' --exclude='kdecache*' $VAREXCLUDES -a /var/. $WORKDIR/dummysys/var/.
    rsync $VAREXCLUDES -a /etc/. $WORKDIR/dummysys/etc/.

    #Adding packages location to sources
    DISKINFONAME=$(echo $LIVECDLABEL | awk '{print $1}')
    DISTRIB_RELEASE=$(echo $LIVECDLABEL | awk '{print $2}')
    # ***rik: below sets environment variables in this script from lsb-release
    . /etc/lsb-release

    if [ -e $WORKDIR/dummysys/etc/apt/sources.list.wasta ]; then
        log_msg "Wasta-offline detected: use original sources.list"
        mv $WORKDIR/dummysys/etc/apt/sources.list.wasta $WORKDIR/dummysys/etc/apt/sources.list
    fi
    if [ -x $WORKDIR/dummysys/etc/apt/sources.list.d.wasta/ ] \
    && [ -x $WORKDIR/dummysys/etc/apt/sources.list.d/ ]; then
        log_msg "Wasta-offline detected: use original sources.list.d"
        mv $WORKDIR/dummysys/etc/apt/sources.list.d.wasta/* $WORKDIR/dummysys/etc/apt/sources.list.d/
        rm -rf $WORKDIR/dummysys/etc/apt/sources.list.d.wasta
    fi
    if [ -x $WORKDIR/dummysys/var/lib/apt/lists.wasta/ ] \
    && [ -x $WORKDIR/dummysys/var/lib/apt/lists/ ]; then
        log_msg "Wasta-offline detected: use original apt/lists"
        mv $WORKDIR/dummysys/var/lib/apt/lists.wasta/* $WORKDIR/dummysys/var/lib/apt/lists/
        rm -rf $WORKDIR/dummysys/var/lib/apt/lists.wasta/
        rm -f  $WORKDIR/dummysys/var/lib/apt/lists/*_wasta-offline_*
    fi
    # ***rik: we remove any existing cdrom because casper auto mounts the cdrom from
    #         the livecd at boot time, so no need to manually add: manually adding
    #         also not supported because will get complaints that cdroms can only
    #         be added using apt-cdrom (which I think casper is using at boot time).
    sed -i '/cdrom:/d' $WORKDIR/dummysys/etc/apt/sources.list &> /dev/null

    #Copying grub config
    cp /etc/default/grub $WORKDIR/dummysys/etc/default/grub

    # ***rik: default to not show grub boot menu: ubiquity is smart enough
    #   to modify to show again if other OSs are detected
    sed -i -e "s@.*\(GRUB_TIMEOUT_STYLE\)=.*@\1=hidden@" \
        $WORKDIR/dummysys/etc/default/grub

    #rik: If first word of GRUB_DISTRIBUTOR is not 'Ubuntu' there will be
    #   EFI boot problems for Ubuntu 18.04 based ISOs.
    if [[ $LIVECDLABEL != "Ubuntu "* ]];
    then
        sed -i -e "s@.*\(GRUB_DISTRIBUTOR\)=.*@\1=\"Ubuntu $LIVECDLABEL\"@" \
            $WORKDIR/dummysys/etc/default/grub
    else
        sed -i -e "s@.*\(GRUB_DISTRIBUTOR\)=.*@\1=\"$LIVECDLABEL\"@" \
            $WORKDIR/dummysys/etc/default/grub
    fi

    log_msg "Cleaning up files not needed for the live cd in $WORKDIR/dummysys"
    rm -rf $WORKDIR/dummysys/etc/apt/sources.list.d/*.save &> /dev/null
# ***rik rm -rf $WORKDIR/dummysys/etc/apt/apt.conf.d/* &> /dev/null
# ***rik rm -rf $WORKDIR/dummysys/etc/apt/preferences.d/* &> /dev/null
# ***rik rm -rf $WORKDIR/dummysys/var/lib/apt/lists/* -vf &> /dev/null
    rm -rf $WORKDIR/dummysys/var/lib/apt/lists/lock &> /dev/null
    rm -rf $WORKDIR/dummysys/var/cache/apt/archives/* &> /dev/null
    rm -rf $WORKDIR/dummysys/var/lib/ureadahead/pack &> /dev/null
    rm -f $WORKDIR/dummysys/var/lib/update-notifier/user.d/* &> /dev/null
    rm -f $WORKDIR/dummysys/etc/X11/xorg.conf*
#    rm -f $WORKDIR/dummysys/etc/ timezone
    rm -f $WORKDIR/dummysys/etc/{hosts,hostname,mtab*,fstab}
    if [ ! -L $WORKDIR/dummysys/etc/resolv.conf ]; then
        rm -f $WORKDIR/dummysys/etc/resolv.conf
    fi
    rm -f $WORKDIR/dummysys/etc/udev/rules.d/70-persistent*
    rm -f $WORKDIR/dummysys/etc/cups/ssl/{server.crt,server.key}
    rm -f $WORKDIR/dummysys/etc/ssh/*key*
    rm -f $WORKDIR/dummysys/var/lib/dbus/machine-id
    rsync -a /dev/urandom $WORKDIR/dummysys/dev/
    find $WORKDIR/dummysys/var/log/ -type f -exec rm -f {} \;
    find $WORKDIR/dummysys/var/lock/ -type f -exec rm -f {} \;
    find $WORKDIR/dummysys/var/backups/ -type f -exec rm -f {} \;
    find $WORKDIR/dummysys/var/tmp/ -type f -exec rm -f {} \;
    [ -d $WORKDIR/dummysys/var/crash/ ] &&
        find $WORKDIR/dummysys/var/crash/ -type f -exec rm -f {} \;
    find $WORKDIR/dummysys/var/lib/ubiquity/ -type f -exec rm -f {} \;

    if [ "$1" == "dist" ]; then

        rm -f $WORKDIR/dummysys/etc/{group,passwd,shadow,shadow-,gshadow,gshadow-}
        rm -f $WORKDIR/dummysys/etc/wicd/{wired-settings.conf,wireless-settings.conf}
        rm -rf $WORKDIR/dummysys/etc/NetworkManager/system-connections/*
        rm -f $WORKDIR/dummysys/etc/printcap
        rm -f $WORKDIR/dummysys/etc/cups/printers.conf
        touch $WORKDIR/dummysys/etc/printcap
        touch $WORKDIR/dummysys/etc/cups/printers.conf
        rm -rf $WORKDIR/dummysys/var/cache/gdm/*
        rm -rf $WORKDIR/dummysys/var/lib/sudo/*
        rm -rf $WORKDIR/dummysys/var/lib/AccountsService/users/*
        rm -rf $WORKDIR/dummysys/var/lib/kdm/*
        rm -rf $WORKDIR/dummysys/var/run/console/*

        rm -f $WORKDIR/dummysys/etc/gdm/gdm.conf-custom
        if [ -d /etc/"${BRAND_ETC}"/gdm/ ]; then
            #Setting up auto timed login of live user for GDM3
            if [ -f /etc/gdm/custom.conf ]; then
                log_msg "WARNING: removing your /etc/gdm/custom.conf to support LiveCD autologin"
            fi
            mkdir -p $WORKDIR/dummysys/etc/gdm
            cp /etc/"${BRAND_ETC}"/gdm/custom.conf $WORKDIR/dummysys/etc/gdm
            sed -i "s/LIVEUSER/$LIVEUSER/g" $WORKDIR/dummysys/etc/gdm/custom.conf
            chmod 755 $WORKDIR/dummysys/etc/gdm/custom.conf
        fi
        if [ -d /etc/"${BRAND_ETC}"/mdm/ ]; then
            #Setting up auto login of live user for MDM
            if [ -f /etc/mdm/custom.conf ]; then
               log_msg "WARNING: removing your /etc/mdm/mdm.conf to support LiveCD autologin"
            fi
            mkdir -p $WORKDIR/dummysys/etc/mdm
            cp /etc/"${BRAND_ETC}"/mdm/mdm.conf $WORKDIR/dummysys/etc/mdm/mdm.conf
            sed -i "s/LIVEUSER/$LIVEUSER/g" $WORKDIR/dummysys/etc/mdm/mdm.conf
            chmod 755 $WORKDIR/dummysys/etc/mdm/mdm.conf
        fi

        find $WORKDIR/dummysys/var/mail/ -type f -exec rm -f {} \;
        SPOOL_KEEP=""
        #preserve libreoffice extensions
        SPOOL_KEEP="${SPOOL_KEEP} -path $WORKDIR/dummysys/var/spool/libreoffice -prune "
        #preserve critical "at" file
        SPOOL_KEEP="${SPOOL_KEEP} ! -wholename $WORKDIR/dummysys/var/spool/cron/atjobs/.SEQ "
        find $WORKDIR/dummysys/var/spool/ -type f ${SPOOL_KEEP} -exec rm -f {} \;
        if [ ! -d /run ]; then
            find $WORKDIR/dummysys/var/run/ -type f -exec rm -f {} \;
        else
            unlink $WORKDIR/dummysys/var/run
            cd $WORKDIR/dummysys/var
            ln -sf ../run run
        fi

        # ***rik: creating empty placeholder files this way has proved problematic.
        #   The files are owned by root:root which isn't right.
        #   They all seem to autocreate just fine, so unsure why the original
        #   author thought it necessary to create these placeholder files.
        # for i in dpkg.log lastlog mail.log syslog auth.log daemon.log faillog lpr.log mail.warn user.log boot debug mail.err messages wtmp bootstrap.log dmesg kern.log mail.info
        #do
        #    touch $WORKDIR/dummysys/var/log/${i}
        #done

        log_msg "Cleaning up passwd, group, shadow and gshadow files for the live system"
        grep '^[^:]*:[^:]*:[0-9]:' /etc/passwd > $WORKDIR/dummysys/etc/passwd
        grep '^[^:]*:[^:]*:[0-9][0-9]:' /etc/passwd >> $WORKDIR/dummysys/etc/passwd
        grep '^[^:]*:[^:]*:[0-9][0-9][0-9]:' /etc/passwd >> $WORKDIR/dummysys/etc/passwd
        grep '^[^:]*:[^:]*:[3-9][0-9][0-9][0-9][0-9]:' /etc/passwd >> $WORKDIR/dummysys/etc/passwd

        grep '^[^:]*:[^:]*:[0-9]:' /etc/group > $WORKDIR/dummysys/etc/group
        grep '^[^:]*:[^:]*:[0-9][0-9]:' /etc/group >> $WORKDIR/dummysys/etc/group
        grep '^[^:]*:[^:]*:[0-9][0-9][0-9]:' /etc/group >> $WORKDIR/dummysys/etc/group
        grep '^[^:]*:[^:]*:[3-9][0-9][0-9][0-9][0-9]:' /etc/group >> $WORKDIR/dummysys/etc/group

        grep '^[^:]*:[^:]*:[5-9][0-9][0-9]:' /etc/passwd | awk -F ":" '{print $1}'> $WORKDIR/tmpusers1
        grep '^[^:]*:[^:]*:[1-9][0-9][0-9][0-9]:' /etc/passwd | awk -F ":" '{print $1}'> $WORKDIR/tmpusers2
        grep '^[^:]*:[^:]*:[1-2][0-9][0-9][0-9][0-9]:' /etc/passwd | awk -F ":" '{print $1}'> $WORKDIR/tmpusers3

        cat $WORKDIR/tmpusers1 $WORKDIR/tmpusers2 $WORKDIR/tmpusers3 > $WORKDIR/tmpusers
        rm -f $WORKDIR/tmpusers[0-9] &> /dev/null

        #cp /etc/shadow $WORKDIR/dummysys/etc/shadow
        #cp /etc/gshadow $WORKDIR/dummysys/etc/gshadow

        cat $WORKDIR/tmpusers | while read LINE ;do

            echo $LINE | xargs -i sed -e 's/,{}$//g' $WORKDIR/dummysys/etc/group > $WORKDIR/dummysys/etc/group.new1
            echo $LINE | xargs -i sed -e 's/,{},/,/g' $WORKDIR/dummysys/etc/group.new1 > $WORKDIR/dummysys/etc/group.new2
            echo $LINE | xargs -i sed -e 's/:{}$/:/g' $WORKDIR/dummysys/etc/group.new2 > $WORKDIR/dummysys/etc/group.new3
            echo $LINE | xargs -i sed -e 's/:{},/:/g' $WORKDIR/dummysys/etc/group.new3 > $WORKDIR/dummysys/etc/group

            # /etc/shadow and /etc/gshadow needed for rescue mode boot root access - removed due to user creation issues for live boot

           # echo $LINE | xargs -i sed -e '/^{}:/d' $WORKDIR/dummysys/etc/shadow > $WORKDIR/dummysys/etc/shadow.new
            #sed -i -e 's/root:x:/root:!:/g' $WORKDIR/dummysys/etc/shadow.new
            #mv $WORKDIR/dummysys/etc/shadow.new $WORKDIR/dummysys/etc/shadow

            #echo $LINE | xargs -i sed -e '/^{}:/d' $WORKDIR/dummysys/etc/gshadow > $WORKDIR/dummysys/etc/gshadow.new1
            #echo $LINE | xargs -i sed -e 's/,{}$//g' $WORKDIR/dummysys/etc/gshadow.new1 > $WORKDIR/dummysys/etc/gshadow.new2
            #echo $LINE | xargs -i sed -e 's/,{},/,/g' $WORKDIR/dummysys/etc/gshadow.new2 > $WORKDIR/dummysys/etc/gshadow.new3
            #echo $LINE | xargs -i sed -e 's/:{}$/:/g' $WORKDIR/dummysys/etc/gshadow.new3 > $WORKDIR/dummysys/etc/gshadow.new4
            #echo $LINE | xargs -i sed -e 's/:{},/:/g' $WORKDIR/dummysys/etc/gshadow.new4 > $WORKDIR/dummysys/etc/gshadow

            rm -f $WORKDIR/dummysys/etc/group.new* &> /dev/null
        done
    fi

    # make sure the adduser and autologin functions of casper as set according to the mode
    log_msg "Making sure adduser and autologin functions of casper are set properly"
    [ "$1" == "dist" ] && [ ! -d $WORKDIR/dummysys/home ] && mkdir $WORKDIR/dummysys/home
    [ "$1" == "dist" ] && chmod 755 /usr/share/initramfs-tools/scripts/casper-bottom/*adduser /usr/share/initramfs-tools/scripts/casper-bottom/*autologin
    [ "$1" == "backup" ] && [ -d $WORKDIR/dummysys/home ] && rm -rf $WORKDIR/dummysys/home
    [ "$1" == "backup" ] && chmod 644 /usr/share/initramfs-tools/scripts/casper-bottom/*adduser /usr/share/initramfs-tools/scripts/casper-bottom/*autologin

    #virtualbox creates a user with id 999 which conflicts with casper's default
    #  causing login to fail
    UID_999=$(getent passwd 999 | awk -F: '{ print $1}')
    if [ "${UID_999}" != "" ]; then
        if [ "$(getent passwd 990)" == "" ]; then
            log_msg "   avoiding conflict with ${UID_999}.  Using uid 990..."
            sed -i -e 's@user-uid 999@user-uid 990@' \
                /usr/share/initramfs-tools/scripts/casper-bottom/*adduser
        else
            echo && echo
            log_msg "*  ERROR: problem finding a free userid. "
            log_msg "*     Conflict with ${UID_999}"
            echo && echo
        fi
    fi

    # copy over some of the necessary stuff for the livecd

    #copy any preseed files
    cp /etc/"${BRAND_ETC}"/preseed/* $WORKDIR/ISOTMP/preseed/

    #BOOT Type is isolinux
    log_msg "Copying memtest86+ for the live system"
    cp /boot/memtest86+.bin $WORKDIR/ISOTMP/install/memtest

    #EFI BOOT
    if [ -d /usr/lib/"${BRAND_NAME}" ]; then
        log_msg "Copying EFI Boot for the live system"
        cp -a /usr/lib/"${BRAND_NAME}"/boot $WORKDIR/ISOTMP/
        cp -a /usr/lib/"${BRAND_NAME}"/EFI $WORKDIR/ISOTMP/
        #cp $WORKDIR/ISOTMP/EFI/BOOT/BOOTx64.EFI $WORKDIR/ISOTMP/EFI/BOOT/fallback.efi
        sed -i "s/__LIVECDLABEL__/$LIVECDLABEL/g" $WORKDIR/ISOTMP/boot/grub/grub.cfg
        sed -i "s/__LIVECDLABEL__/$LIVECDLABEL/g" $WORKDIR/ISOTMP/boot/grub/loopback.cfg
    fi

    #Downloading packages for offline install
    log_msg "Downloading packages for CD"
    mkdir -p $WORKDIR/ISOTMP/pool
    cd $WORKDIR/ISOTMP/pool

    if [ -x /etc/"${BRAND_ETC}"/pool/ ]; then
        cp -a /etc/"${BRAND_ETC}"/pool $WORKDIR/ISOTMP/
    fi

    #if ANY package is unavailable, the whole block of downloads will fail.
    apt-get download -q \
        b43-fwcutter \
        bcmwl-kernel-source \
        dkms

    apt-get download -q \
        efibootmgr \
        grub-common \
        grub-efi \
        grub-efi-ia32 \
        grub-efi-ia32-bin \
        grub-pc\
        grub-pc-bin \
        grub2-common \
        grub-gfxpayload-lists \
        secureboot-db \
        shim shim-signed

    #These packages probably are not available on 32bit, so download separately
    if [ "${ARCH}" == "amd64" ]; then
        apt-get download -q \
            grub-efi-amd64 \
            grub-efi-amd64-bin \
            grub-efi-amd64-signed
    fi

    #libefivar0 and mokutil added by Pinguy in 4.3?  
    log_msg "  download efi helper files (optional - may not be available)"
    #example: not available in 12.04, so download separately
    apt-get download -q libefivar0
    apt-get download -q libefivar1
    apt-get download -q mokutil

    mkdir -p $WORKDIR/ISOTMP/dists
    cd $WORKDIR/ISOTMP/

    # ***rik: previously, was sending &> to /dev/null which meant Packages was empty!
    log_msg "  generating package list for local packages"
    dpkg-scanpackages pool > dists/Packages
    gzip -9c dists/Packages > dists/Packages.gz

    # check and see if they have a custom isolinux already setup. eg. they copied over
    # the isolinux folder from their original livecd or made a custom one for their distro

    if [ ! -f /etc/"${BRAND_ETC}"/customisolinux/isolinux.cfg ]; then
        log_msg "Creating isolinux setup for the live system"
        find /usr -name 'isolinux.bin' -exec cp {} $WORKDIR/ISOTMP/isolinux/ \;
        VESAMENU=$(find /usr -print0 | grep -EzZ --max-count=1 "bios/vesamenu.c32|syslinux/vesamenu.c32"| tr -d '\0')
        if [ -z "$VESAMENU" ]; then
            log_msg "   unable to find vesamenu.c32 - skipping"
        else
            cp $VESAMENU $WORKDIR/ISOTMP/isolinux/
        fi
        LDLINUX=$(find /usr -print0 | grep -EzZ --max-count=1 "bios/ldlinux.c32|syslinux/ldlinux.c32"| tr -d '\0')
        if [ -z "$LDLINUX" ]; then
            log_msg "   unable to find ldlinux.c32 - skipping"
        else
            cp $LDLINUX $WORKDIR/ISOTMP/isolinux/
        fi
        LIBUTIL=$(find /usr -print0 | grep -EzZ --max-count=1 "bios/libutil.c32|syslinux/libutil.c32"| tr -d '\0')
        if [ -z "$LIBUTIL" ]; then
            log_msg "   unable to find libutil.c32 - skipping"
        else
            cp $LIBUTIL $WORKDIR/ISOTMP/isolinux/
        fi
        LIBCOM=$(find /usr -print0 | grep -EzZ --max-count=1 "bios/libcom32.c32|syslinux/libcom32.c32"| tr -d '\0')
        if [ -z "$LIBCOM" ]; then
            log_msg "   unable to find libcom32.c32 - skipping"
        else
            cp $LIBCOM $WORKDIR/ISOTMP/isolinux/
        fi
        MENU=$(find /usr -print0 | grep -EzZ --max-count=1 "bios/menu.c32|syslinux/menu.c32" | tr -d '\0')
        if [ -z "$MENU" ]; then
            log_msg "   unable to find menu.c32 - skipping"
        else
            cp $MENU $WORKDIR/ISOTMP/isolinux/
        fi
        # setup isolinux for the livecd
        sed -e 's/__LIVECDLABEL__/'"$LIVECDLABEL"'/g' /etc/"${BRAND_ETC}"/isolinux/isolinux.cfg.vesamenu > \
        $WORKDIR/ISOTMP/isolinux/isolinux.cfg
        if [ "$SPLASHPNG" ]; then
            cp $SPLASHPNG $WORKDIR/ISOTMP/isolinux/splash.png
        fi
    else
        log_msg "Copying your custom isolinux setup to the live system"
        cp /etc/"${BRAND_ETC}"/customisolinux/* $WORKDIR/ISOTMP/isolinux/ &> /dev/null
    fi

    log_msg "Setting the README.diskdefines file to use ARCH $ARCH"

    cat > $WORKDIR/ISOTMP/README.diskdefines <<FOO
#define DISKNAME  $LIVECDLABEL
#define TYPE  binary
#define TYPEbinary  1
#define ARCH  $ARCH
#define ARCH$ARCH  1
#define DISKNUM  1
#define DISKNUM1  1
#define TOTALNUM  0
#define TOTALNUM0  1
FOO
    cp $WORKDIR/ISOTMP/README.diskdefines $WORKDIR/ISOTMP/casper/README.diskdefines

    sleep 1

    # Step 4 - Make the filesystem.manifest and filesystem.manifest-desktop
    log_msg "Creating filesystem.manifest and filesystem.manifest-desktop"
    dpkg-query -W --showformat='${Package} ${Version}\n' > $WORKDIR/ISOTMP/casper/filesystem.manifest

    cp $WORKDIR/ISOTMP/casper/filesystem.manifest $WORKDIR/ISOTMP/casper/filesystem.manifest-desktop
    # Suggested by lkjoel from Ubuntu Forums - Joel Leclerc to remove the frontend so the Install menu item is not on the installed system
    sed -i '/ubiquity-frontend/d' $WORKDIR/ISOTMP/casper/filesystem.manifest-desktop

    sleep 1

    # Step 5 - Prepare casper.conf depending on whether this is a backup or dist

    if [ "$1" == "backup" ]; then
        BACKUPEXCLUDES=""
        log_msg "Excluding folders from the backup that will cause issues"

        for bi in $(ls /home); do
            if [ -d /home/$bi/.gvfs ]; then
                BACKUPEXCLUDES="$BACKUPEXCLUDES /home/$bi/.gvfs "
            fi
            if [ -d /home/$bi/.cache ]; then
                BACKUPEXCLUDES="$BACKUPEXCLUDES /home/$bi/.cache "
            fi
            if [ -d /home/$bi/.thumbnails ]; then
                BACKUPEXCLUDES="$BACKUPEXCLUDES /home/$bi/.thumbnails "
            fi
            if [ -d /home/$bi/.local/share/gvfs-metadata ]; then
                BACKUPEXCLUDES="$BACKUPEXCLUDES /home/$bi/.local/share/gvfs-metadata "
            fi
            if [ -d /home/$bi/.local/gvfs-metadata ]; then
                BACKUPEXCLUDES="$BACKUPEXCLUDES /home/$bi/.local/gvfs-metadata "
            fi
            if [ -d /home/$bi/.local/share/Trash ]; then
                BACKUPEXCLUDES="$BACKUPEXCLUDES /home/$bi/.local/share/Trash "
            fi
        done
        LIVEUSER="$(who -u | grep -v root | cut -d " " -f1| uniq)"
        if [ "$(who -u | grep -v root | cut -d " " -f1| uniq | wc -l)" != "1" ]; then
            LIVEUSER="$(grep '^[^:]*:[^:]*:1000:' /etc/passwd | awk -F ":" '{ print $1 }')"
        fi
        if [ "$LIVEUSER" == "" ]; then
            log_msg "Can't determine which user to use. Please logoff all users except for your main user and try again. Exiting."
            exit 1
        fi
        LIVEHOME=$(grep $LIVEUSER /etc/passwd | awk -F ":" '{print $6}')
        if [ "$BACKUPSHOWINSTALL" == "1" ]; then
            # copy the install icon to the sudo users desktop
            log_msg "Copying the install icon to the desktop of $LIVEUSER"
            UBIQUITYDESKTOP=$(find /usr -name ubiquity*.desktop | head -1)
            if [ "$UBIQUITYDESKTOP" ]; then
                install -d -o $LIVEUSER -g $LIVEUSER $LIVEHOME/Desktop &> /dev/null
                install -D -o $LIVEUSER -g $LIVEUSER $UBIQUITYDESKTOP $LIVEHOME/Desktop/ &> /dev/null
                #casper modifier used to change desktop installer name
                sed -i \
                    -e "s/RELEASE/$LIVECDLABEL/" \
                  "$LIVEHOME/Desktop/$(basename $UBIQUITYDESKTOP)" &> /dev/null
                #17.10+ support: mark ubiquity.desktop as trusted executable.
                sed -i \
                    -e "\|ubiquity.desktop| s|su .* -c|su $LIVEUSER -c|" \
                    -e "\|ubiquity.desktop| s|/home/[^/]+/|/$LIVEHOME/|" \
                  /etc/init.d/"${BRAND_INIT}-firstboot"
            fi
        fi
    fi
    log_msg "Creating the casper.conf file."
    # Added FLAVOUR= as the new casper live boot will make it the first word from the Live CD Name if FLAVOUR is not set
    cat > /etc/casper.conf <<FOO
# This file should go in /etc/casper.conf
# Supported variables are:
# USERNAME, USERFULLNAME, HOST, BUILD_SYSTEM

export USERNAME="$LIVEUSER"
export USERFULLNAME="Live session user"
export HOST="$LIVEUSER"
export BUILD_SYSTEM="Ubuntu"
export FLAVOUR="$LIVEUSER"
FOO
    cp /etc/casper.conf $WORKDIR/dummysys/etc/

    sleep 1

    # if the mode is dist then renumber the uid's for any user with a uid greater than 1000
    # and make the passwdrestore file so the uid's are restored before the script finishes
    # if this is not done, the livecd user will not be created properly
    log_msg "Checking and setting user-setup-apply for the live system"
    if [ "$1" == "dist" ]; then
        # make sure user-setup-apply is present in case backup mode was last used
        if [ -f /usr/lib/ubiquity/user-setup/user-setup-apply.orig ]; then
            cp /usr/lib/ubiquity/user-setup/user-setup-apply.orig /usr/lib/ubiquity/user-setup/user-setup-apply
        fi
    else
        # since this is backup mode, prevent user-setup-apply from running during install
        if [ ! -f /usr/lib/ubiquity/user-setup/user-setup-apply.orig ]; then
            mv /usr/lib/ubiquity/user-setup/user-setup-apply /usr/lib/ubiquity/user-setup/user-setup-apply.orig
        fi
        echo "exit 0"> /usr/lib/ubiquity/user-setup/user-setup-apply
        chmod 755 /usr/lib/ubiquity/user-setup/user-setup-apply
    fi

    sleep 1

    log_msg "Setting up casper and ubiquity options for $1 mode"

    # make a new initial ramdisk including the casper scripts
    log_msg "Creating a new initial ramdisk for the live system"
    mkinitramfs -o /boot/initrd.img-$(uname -r) $(uname -r)

    log_msg "Copying your kernel and initrd for the livecd"
    cp /boot/vmlinuz-$(uname -r) $WORKDIR/ISOTMP/casper/vmlinuz
    cp /boot/initrd.img-$(uname -r) $WORKDIR/ISOTMP/casper/initrd.gz
    if [ ! -f $WORKDIR/ISOTMP/casper/vmlinuz ]; then
        log_msg "Missing valid kernel. Exiting"
        exit 1
    fi

###########  section from BOHDIBUILDER that may be useful for UEFI ##########
#    # first check to see if it's 64bit,
#    # 64bit needs vmlinuz.efi
#    case $ARCH in
#        amd64 ) # 64bit needs vmlinuz.efi
#            log_msg "Creating casper/vmlinuz.efi"
#            cp -v /boot/vmlinuz-$(uname -r) $WORKDIR/ISOTMP/casper/vmlinuz.efi
#            sed -i 's/vmlinuz$/vmlinuz\.efi/g' $WORKDIR/ISOTMP/isolinux/isolinux.cfg
#        ;;
#        *) # everything else needs just vmlinuz
#            log_msg "Creating casper/vmlinuz"
#            cp -v /boot/vmlinuz-$(uname -r) $WORKDIR/ISOTMP/casper/vmlinuz
#            sed -i 's/vmlinuz\.efi$/vmlinuz/g' $WORKDIR/ISOTMP/isolinux/isolinux.cfg
#        ;;
#    esac
#    # Copy initrd into casper
#    cp -v /boot/initrd.img-$(uname -r) $WORKDIR/ISOTMP/casper/initrd.lz
#
#    ## See bohdibuilder code for process to create initrd.lz from initrd.img...
#
#    #exit if missing... either vmlinuz or vmlinuz.efi
#    if [ ! -f $WORKDIR/ISOTMP/casper/vmlinuz.efi ]; then
#        if [ ! -f $WORKDIR/ISOTMP/casper/vmlinuz ]; then
#            log_msg "Missing valid kernel. Exiting"
#            exit 1
#        fi
#    fi
#    #exit if missing... initrd.lz
#    if [ ! -f $WORKDIR/ISOTMP/casper/initrd.lz ]; then
#        log_msg "Missing valid initial ramdisk. Exiting"
#        exit 1
#    fi
###########  END section from BOHDIBUILDER #######

    if [ ! -f $WORKDIR/ISOTMP/casper/initrd.gz ]; then
        log_msg "Missing valid initial ramdisk. Exiting"
        exit 1
    fi

    # Step 6 - Make filesystem.squashfs

    if [ -f $WORKDIR/ISOTMP/casper/filesystem.squashfs ]; then
        rm -f $WORKDIR/ISOTMP/casper/filesystem.squashfs &> /dev/null
    fi

    log_msg "Creating filesystem.squashfs   ... this will take a while so be patient"

    REALFOLDERS=""

    # Includes Addition
    for d in $INCLUDES;
    do
        # remove folders from dummysys so that real ones would be included
        rmdir --ignore-fail-on-non-empty  $WORKDIR/dummysys${d}
    done

    for d in $(ls -d $WORKDIR/dummysys/*); do
        REALFOLDERS="$REALFOLDERS $d"
    done

    if [ "$1" == "backup" ]; then

        for d in $(ls / | grep -v etc | grep -v run | grep -v tmp | grep -v sys | grep -v var | grep -v dev | grep -v media | grep -v mnt | grep -v lost+found | grep -v proc); do
            REALFOLDERS="$REALFOLDERS /$d"
        done
    else

        for d in $(ls / | grep -v etc | grep -v run | grep -v tmp | grep -v sys | grep -v var | grep -v dev | grep -v media | grep -v mnt | grep -v lost+found | grep -v proc | grep -v home); do
            REALFOLDERS="$REALFOLDERS /$d"
        done
    fi

    #17.04+ defaults to having a swapfile instead of a swap partition. Exclude it.
    SWAPFILE="$(grep $' file\t' /proc/swaps | awk '{print $1}')"

    ROOT_MODE_OPT=""  #don't set root level permissions to 777 - only available in 4.4+. This benefits Calamares installer.
    MKSQUASHFS_VERSION=$(mksquashfs -version | grep "mksquashfs version" | awk  '{print $3}')
    if [ "$MKSQUASHFS_VERSION" ] && [ $(echo "$MKSQUASHFS_VERSION >= 4.4" | bc) -eq 1 ]; then
        ROOT_MODE_OPT=" -root-mode 755"
    fi

    mksquashfs $INCLUDES $REALFOLDERS $WORKDIR/ISOTMP/casper/filesystem.squashfs -no-duplicates $ROOT_MODE_OPT $SQUASHFSOPTS -e root/.local/Trash root/.thumbnails root/.cache root/.bash_history root/.lesshst root/.nano_history /boot/efi/EFI /boot/grub $BASEWORKDIR $EXCLUDES $SWAPFILE 2>>$WORKDIR/"${BRAND_LOG}"

    sleep 1

    #add some stuff the log in case of problems so I can troubleshoot it easier
    log_msg "Updating the ${BRAND_LOG}"
    echo "--------------------------------------------" >>$WORKDIR/"${BRAND_LOG}"
    echo "Mount information" >>$WORKDIR/"${BRAND_LOG}"
    mount >>$WORKDIR/"${BRAND_LOG}"
    echo "--------------------------------------------" >>$WORKDIR/"${BRAND_LOG}"
    echo "Disk size information" >>$WORKDIR/"${BRAND_LOG}"
    df -h >>$WORKDIR/"${BRAND_LOG}"
    echo "--------------------------------------------" >>$WORKDIR/"${BRAND_LOG}"
    echo "Casper Script info" >>$WORKDIR/"${BRAND_LOG}"
    ls -l /usr/share/initramfs-tools/scripts/casper-bottom/ >>$WORKDIR/"${BRAND_LOG}"
    echo "--------------------------------------------" >>$WORKDIR/"${BRAND_LOG}"
    echo "/etc/"${BRAND_ETC}"/"${BRAND_NAME}.conf" info" >>$WORKDIR/"${BRAND_LOG}"
    cat /etc/"${BRAND_ETC}"/"${BRAND_NAME}.conf" >>$WORKDIR/"${BRAND_LOG}"
    echo "--------------------------------------------" >>$WORKDIR/"${BRAND_LOG}"
    echo "/etc/casper.conf info" >>$WORKDIR/"${BRAND_LOG}"
    cat /etc/casper.conf >>$WORKDIR/"${BRAND_LOG}"
    echo "--------------------------------------------" >>$WORKDIR/"${BRAND_LOG}"
    echo "/etc/passwd info" >>$WORKDIR/"${BRAND_LOG}"
    cat $WORKDIR/dummysys/etc/passwd >>$WORKDIR/"${BRAND_LOG}"
    echo "--------------------------------------------" >>$WORKDIR/"${BRAND_LOG}"
    echo "/etc/group info" >>$WORKDIR/"${BRAND_LOG}"
    cat $WORKDIR/dummysys/etc/group >>$WORKDIR/"${BRAND_LOG}"
    echo "--------------------------------------------" >>$WORKDIR/"${BRAND_LOG}"
    echo "/etc/X11/default-display-manager info" >>$WORKDIR/"${BRAND_LOG}"
    cat $WORKDIR/dummysys/etc/X11/default-display-manager >>$WORKDIR/"${BRAND_LOG}"
    echo "--------------------------------------------" >>$WORKDIR/"${BRAND_LOG}"
    echo "/etc/skel info" >>$WORKDIR/"${BRAND_LOG}"
    find /etc/skel >>$WORKDIR/"${BRAND_LOG}"
    echo "--------------------------------------------" >>$WORKDIR/"${BRAND_LOG}"
    echo "lsb-release info" >>$WORKDIR/"${BRAND_LOG}"
    cat $WORKDIR/dummysys/etc/lsb-release >>$WORKDIR/"${BRAND_LOG}"
    echo "--------------------------------------------" >>$WORKDIR/"${BRAND_LOG}"
    echo "${BRAND_NAME} version info" >>$WORKDIR/"${BRAND_LOG}"
    cat $WORKDIR/dummysys/etc/"${BRAND_ETC}"/"${BRAND_NAME}.version" >>$WORKDIR/"${BRAND_LOG}"
    echo "--------------------------------------------" >>$WORKDIR/"${BRAND_LOG}"
    echo "ISOTMP info" >>$WORKDIR/"${BRAND_LOG}"
    ls -Rl $WORKDIR/ISOTMP >>$WORKDIR/"${BRAND_LOG}"
    echo "--------------------------------------------" >>$WORKDIR/"${BRAND_LOG}"
    echo "$WORKDIR/tmpusers info" >>$WORKDIR/"${BRAND_LOG}"
    cat $WORKDIR/tmpusers >>$WORKDIR/"${BRAND_LOG}"
    echo "--------------------------------------------" >>$WORKDIR/"${BRAND_LOG}"
    echo "Command-line options = $@" >>$WORKDIR/"${BRAND_LOG}"
    echo "--------------------------------------------" >>$WORKDIR/"${BRAND_LOG}"

    # cleanup the install icons as they aren't needed on the current system
    if [ "$1" == "backup" ]; then
        log_msg "Cleaning up the install icon from the user desktops"
        rm -rf /home/*/Desktop/ubiquity*.desktop &> /dev/null
    fi

    #remove frontend from the system so the Install menu item does not appear.
    log_msg "Removing the ubiquity frontend as it has been included and is not needed on the normal system"
    apt-get -y -q remove ubiquity-frontend-kde &> /dev/null
    apt-get -y -q remove ubiquity-frontend-gtk &> /dev/null

    #Remove Boot-Repair if only installed here
    if [ "$REMOVE_BOOT_REPAIR" == "YES" ];
    then
        log_msg "Removing Boot-Repair: it was only installed for the Live System"
        apt-get -y -q remove boot-repair &> /dev/null
    fi

    #Remove CHNTPW if only installed here
    if [ "$REMOVE_CHNTPW" == "YES" ];
    then
        log_msg "Removing CHNTPW: it was only installed for the Live System"
        apt-get -y -q remove chntpw &> /dev/null
    fi

    sleep 1

    #checking the size of the compressed filesystem to ensure it meets the iso9660 spec for a single file
    SQUASHFSSIZE=$(ls -s $WORKDIR/ISOTMP/casper/filesystem.squashfs | awk -F " " '{print $1}')
    if [ "$SQUASHFSSIZE" ] && [ "$SQUASHFSSIZE" -gt "3999999" ]; then
        log_msg "The compressed filesystem is larger than genisoimage allows for a single file. You must try to reduce the amount of data you are backing up and try again."
        exit 1
    fi

    #add filesystem size for lucid
    log_msg "Calculating the installed filesystem size for the installer"

    unsquashfs -lls $WORKDIR/ISOTMP/casper/filesystem.squashfs | grep -v " inodes " | grep -v "unsquashfs:" | awk '{print $3}' | grep -v "," > /tmp/size.tmp

    for i in $(cat /tmp/size.tmp); do a=$(($a+$i)); done
    echo $a > $WORKDIR/ISOTMP/casper/filesystem.size

    log_msg "Removing ${BRAND_INIT}-firstboot from system startup"
    update-rc.d -f "${BRAND_INIT}-firstboot" remove
    chmod 644 /etc/init.d/"${BRAND_INIT}-firstboot"
}

iso (){

    CREATEISO="$(which mkisofs)"
    if [ "$CREATEISO" == "" ]; then
        CREATEISO="$(which genisoimage)"
    fi

    # check to see if the cd filesystem exists

    if [ ! -f $WORKDIR/ISOTMP/casper/filesystem.squashfs ]; then
        log_msg "The filesystem.squashfs filesystem is missing.  Either there was a problem creating the compressed filesystem or you are trying to run sudo ${BRAND_BIN} dist iso before sudo ${BRAND_BIN} dist cdfs"
        exit 1
    fi

    SQUASHFSSIZE=$(ls -s $WORKDIR/ISOTMP/casper/filesystem.squashfs | awk -F " " '{print $1}')
    if [ "$SQUASHFSSIZE" -gt "3999999" ]; then
        log_msg "The compressed filesystem is larger than genisoimage allows for a single file. You must try to reduce the amount of data you are backing up and try again."
        exit 1
    fi

    #Step 6.5 - Added by Tim Farley. Make ISO compatible with Ubuntu Startup Disk Creator (Karmic).
    log_msg "Making disk compatible with Ubuntu Startup Disk Creator."
    # ***rik: below sets environment variables in this script from lsb-release
    . /etc/lsb-release
    touch $WORKDIR/ISOTMP/ubuntu
    touch $WORKDIR/ISOTMP/.disk/base_installable
    echo "full_cd/single" > $WORKDIR/ISOTMP/.disk/cd_type
    # starting with 12.04 need to have correct ubuntu version or startup disk creator uses syslinux-legacy which won't work
    echo $DISKINFONAME $DISTRIB_RELEASE - Release $ARCH > $WORKDIR/ISOTMP/.disk/info
    echo $LIVECDURL > $WORKDIR/ISOTMP/.disk/release_notes_url

    # Step 7 - Make md5sum.txt for the files on the livecd - this is used during the
    # checking function of the livecd
    log_msg "Creating md5sum.txt for the livecd/dvd"
    cd $WORKDIR/ISOTMP && find . -type f -print0 | xargs -0 md5sum > md5sum.txt

    #isolinux mode

    # remove files that change and cause problems with checking the disk
    sed -e '/isolinux/d' md5sum.txt > md5sum.txt.new
    sed -e '/md5sum/d' md5sum.txt.new > md5sum.txt
    rm -f md5sum.txt.new &> /dev/null

    sleep 1

    # Step 8 - Make the ISO file
    log_msg "Creating $CUSTOMISO in $WORKDIR"
    ALT_BOOT=""
    if [ -e boot/grub/efi.img ]; then
        ALT_BOOT="-eltorito-alt-boot -e boot/grub/efi.img -no-emul-boot"
    else
        log_msg "   Warning: boot/grub/efi.img is missing!! Skipping EFI boot."
    fi
    $CREATEISO -iso-level 3 -quiet -r -V "$(echo $LIVECDLABEL | cut -c -32)" -cache-inodes -J -l -b isolinux/isolinux.bin -c isolinux/boot.cat -no-emul-boot -boot-load-size 4 -boot-info-table ${ALT_BOOT} -o $WORKDIR/$CUSTOMISO $WORKDIR/ISOTMP &>>$WORKDIR/"${BRAND_LOG}"

    if [ ! -f $WORKDIR/$CUSTOMISO ]; then
        log_msg "The iso was not created. There was a problem. Exiting"
        exit 1
    fi

    # Make the iso hybrid so it can be simply dd copied to a usb flash drive.
    # disable hybrid iso (e.g Easy2Boot doesn't like them)
    if [ "${HYBRIDISO,,}" != "false" ]; then
        log_msg "Making $CUSTOMISO a hybrid iso"
        isohybrid --uefi $WORKDIR/$CUSTOMISO
    fi

    # create the md5 sum file so the user doesn't have to - this is good so the
    # iso file can later be tested to ensure it hasn't become corrupted

    log_msg "Creating .md5 and .sha256 in $WORKDIR"

    cd $WORKDIR
    md5sum $CUSTOMISO > $CUSTOMISO.md5
    sha256sum $CUSTOMISO > $CUSTOMISO.sha256

    sleep 1

    ISOSIZE=$(ls -hs $WORKDIR/$CUSTOMISO | awk '{print $1}')

    log_msg "$WORKDIR/$CUSTOMISO which is $ISOSIZE in size is ready to be burned or tested in a virtual machine."

}

# check to see if either of the iso or cdfs options have been invoked
# and proceed accordingly

case $2 in
    iso )
        iso $@
    ;;
    cdfs )
        cdfs $@
    ;;
    * )
        cdfs $@
        iso $@
    ;;
esac

exit 0
