#!/bin/bash

. /etc/PinguyBuilder/PinguyBuilder.version

# 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

#create PinguyBuilder-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=`grep "REM302" /etc/init.d/PinguyBuilder-firstboot`

if [ "$fbtest" = "" ]; then
    cat > /etc/init.d/PinguyBuilder-firstboot <<FOO
#! /bin/sh
### BEGIN INIT INFO
# Provides:          PinguyBuilder-firstboot
# Required-Start:    \$remote_fs \$syslog \$all
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Run firstboot items for PinguyBuilder 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() {
        #REM302
        if [ "\`cat /proc/cmdline | grep casper\`" = "" ]; then
            [ "\$VERBOSE" != no ] && log_begin_msg "Running PinguyBuilder-firstboot"
            (sleep 60 && update-rc.d -f PinguyBuilder-firstboot remove) &
            sed -i -e 's/root:x:/root:!:/g' /etc/shadow
            rm -rf /home/*/*/ubiquity*.desktop
            rm -rf /usr/share/applications/kde4/ubiquity-kdeui.desktop
            rm -rf /usr/share/applications/ubiquity.desktop
            rm -rf /etc/rc.local
            rm -r /etc/apt
            tar -xf /root/apt.tar.gz -C /
            rm -rf /root/apt.tar.gz
            apt-get -y -q purge firefox-locale-en libreoffice-help-en-*
            update-apt-xapian-index -vf
            #Place your custom commands below this line
            #Example to remove PinguyBuilder and clean up packages

            #apt-get purge pinguybuilder --yes --assume-yes
            #apt-get --yes --assume-yes autoremove

            #Place your custom commands above this line
            ES=\$?
            [ "\$VERBOSE" != no ] && log_end_msg \$ES
            return \$ES
        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


# load the PinguyBuilder.conf file 
. /etc/PinguyBuilder.conf

# if the PinguyBuilder.conf file is incorrect or missing, make sure to set defaults

if [ "$LIVEUSER" = "" ]; then
    #Somebody must have removed the username from the configuration file
    echo 
    #this is a custom live user
    LIVEUSER="custom"
fi

#make sure live user is all lowercase
LIVEUSER="`echo $LIVEUSER | awk '{print tolower ($0)}'`"

if [ "$WORKDIR" = "" ]; then
    BASEWORKDIR="/home/PinguyBuilder"
    WORKDIR="/home/PinguyBuilder/PinguyBuilder"
else
    BASEWORKDIR="$WORKDIR"
    WORKDIR="$WORKDIR/PinguyBuilder"
fi

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

if [ -f $WORKDIR/PinguyBuilder.log ]; then
    rm -f $WORKDIR/PinguyBuilder.log &> /dev/null
fi

touch $WORKDIR/PinguyBuilder.log

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

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

CDBOOTTYPE="ISOLINUX"

if [ "$LIVECDURL" = "" ]; then
    LIVECDURL=""
fi

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

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

if [ "$2" = "cdfs" ]; then
    log_msg "Creating the cd filesystem only"
elif [ "$2" = "iso" ]; then
    log_msg "Creating the iso file only"
elif [ "$2" = "" ]; then
    echo " "
else
    CUSTOMISO="$2"
fi

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

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

case $1  in

    backup)
        log_msg "System Backup Mode Selected"
        ;;

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

    dist)
        log_msg "Distribution Mode Selected"
        ;;


    *)
        echo "Usage of PinguyBuilder $PinguyBuilderVERSION is as follows:"
        echo " "
        echo "   sudo PinguyBuilder backup|clean|dist [cdfs|iso] [filename.iso]"
        echo " "
        echo " "
        echo "Examples:"
        echo " "
        echo "   sudo PinguyBuilder backup   (to make a livecd/dvd backup of your system)"
        echo " "
        echo "   sudo PinguyBuilder backup custom.iso"
        echo "                             (to make a livecd/dvd backup and call the iso custom.iso)" 
        echo " "
        echo "   sudo PinguyBuilder clean    (to clean up temporary files of PinguyBuilder)"
        echo " "
        echo "   sudo PinguyBuilder dist     (to make a distributable livecd/dvd of your system)"
        echo " "
        echo "   sudo PinguyBuilder dist cdfs"
        echo "                             (to make a distributable livecd/dvd filesystem only)"
        echo " "
        echo "   sudo PinguyBuilder 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 on the"
        echo "   cd before the iso is created.  An example of this would be to modify the isolinux"
        echo "   portion of the livecd/dvd"
        echo " "
        exit 1
        ;;

esac

cdfs (){
#Cleaning Apt and backing up
find /etc/apt -type f -iname \*.save -delete &> /dev/null
find /etc/apt -type f -iname \*~ -delete &> /dev/null
tar pczvf /root/apt.tar.gz /etc/apt &> /dev/null
sed -i "s/deb/#deb/g" /etc/apt/sources.list.d/*.list
sed -i "s/deb/#deb/g" /etc/apt/sources.list
echo "deb http://archive.ubuntu.com/ubuntu bionic main restricted" >> /etc/apt/sources.list
echo "deb http://archive.ubuntu.com/ubuntu bionic universe" >> /etc/apt/sources.list
echo "deb http://archive.ubuntu.com/ubuntu bionic-backports main restricted universe multiverse" >> /etc/apt/sources.list
echo "deb http://archive.canonical.com/ubuntu bionic partner" >> /etc/apt/sources.list
echo "deb http://archive.ubuntu.com/ubuntu bionic-security main restricted" >> /etc/apt/sources.list
echo "deb http://archive.ubuntu.com/ubuntu bionic-security universe" >> /etc/apt/sources.list
echo "deb http://archive.ubuntu.com/ubuntu bionic-security multiverse" >> /etc/apt/sources.list
    apt-get update  &> /dev/null

log_msg "Enabling PinguyBuilder-firstboot"
chmod 755 /etc/init.d/PinguyBuilder-firstboot
update-rc.d PinguyBuilder-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"


    #Changing caspers user-uid
    sed -i -e 's@user-uid [0-9]*@user-uid 990@' /usr/share/initramfs-tools/scripts/casper-bottom/*adduser
    #sed -i "s/USERNAME=.*/USERNAME=$LIVEUSER/g" /usr/share/initramfs-tools/scripts/casper
    #sed -i "s/HOST=.*/HOST=$LIVEUSER/g" /usr/share/initramfs-tools/scripts/casper
    #removing popularity-contest as it causes a problem when installing with ubiquity
    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

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

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

    # check whether system is gnome or kde based to load the correct ubiquity 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 purge ubiquity-casper &> /dev/null
        apt-get -y -q purge ubiquity &> /dev/null
        apt-get -y -q purge ubiquity-ubuntu-artwork &> /dev/null
        apt-get -y -q remove ubiquity-frontend-kde &> /dev/null
        apt-get -y -q install ubiquity-frontend-kde &> /dev/null
        apt-get -y -q remove ubiquity-frontend-gtk &> /dev/null
        chmod +x /usr/share/applications/kde4/ubiquity-kdeui.desktop &> /dev/null
        sed -i "s/ubiquity kde_ui/pkexec ubiquity kde_ui/" /usr/share/applications/kde4/ubiquity-kdeui.desktop
    else
        log_msg "Installing the Ubiquity GTK frontend"
        apt-get -y -q purge ubiquity-casper &> /dev/null
        apt-get -y -q purge ubiquity &> /dev/null
        apt-get -y -q purge ubiquity-ubuntu-artwork &> /dev/null
        apt-get -y -q remove ubiquity-frontend-gtk &> /dev/null
        apt-get -y -q install ubiquity-frontend-gtk &> /dev/null
        apt-get -y -q remove ubiquity-frontend-kde &> /dev/null
        chmod +x /usr/share/applications/ubiquity.desktop &> /dev/null
        sed -i "s/sh -c 'ubiquity gtk_ui'/pkexec ubiquity gtk_ui/" /usr/share/applications/ubiquity.desktop
    fi

    # Replacing Ubiquity icons
    cp -a /etc/PinguyBuilder/icons /usr/share/
    rm -rf /usr/share/icons/hicolor/256x256/apps/ubuntu-logo-icon.png
    ln -s /usr/share/icons/ubuntu-logo-icon.png /usr/share/icons/hicolor/256x256/apps
    chmod 777 /usr/share/icons/hicolor/256x256/apps/ubuntu-logo-icon.png
    chmod 777 /usr/share/icons/ubuntu-logo-icon.png
    gtk-update-icon-cache
    update-icon-caches /usr/share/icons/*
    rm -r /etc/apt &> /dev/null
    tar -xf /root/apt.tar.gz -C / &> /dev/null

log_msg "Cleaning System before building"
    apt-get clean
    rm -rf /opt/teamviewer/config/global.conf
    #apt-get -y -q autoremove &> /dev/null
    #dpkg -l 'linux-*' | sed '/^ii/!d;/'"$(uname -r | sed "s/\(.*\)-\([^0-9]\+\)/\1/")"'/d;s/^[^ ]* [^ ]* \([^ ]*\).*/\1/;/[0-9]/!d' | xargs apt-get -y purge &> /dev/null
    apt-get -y -q purge firefox-locale-* hunspell-* language-pack-gnome-* libreoffice-help-* libreoffice-l10n-* mythes-* &> /dev/null
    #Removing swapfile
    swapoff -v /swapfile &> /dev/null
    rm /swapfile &> /dev/null
    sed -i '/swapfile/d' /etc/fstab &> /dev/null

log_msg "Renaming Distro to $LIVECDLABEL"
    sed -i 's/PRETTY_NAME=.*/PRETTY_NAME="LIVECDLABEL"/g' /usr/lib/os-release
    sed -i "s/LIVECDLABEL/$LIVECDLABEL/g" /usr/lib/os-release

    # Check if they are using lightdm and if it is setup properly for the live default session
    # [ "`grep lightdm /etc/X11/default-display-manager`" != "" ] && [ ! -f /etc/lightdm/lightdm.conf ] && [ ! -f /usr/share/xsessions/ubuntu.desktop ] && echo "Lightdm not setup properly. You must set your default desktop with lightdm prior to remastering" &&  echo "Lightdm not setup properly. You must set your default desktop with lightdm prior to remastering" >> $WORKDIR/PinguyBuilder.log && exit 1

    # prevent the installer from changing the apt sources.list

    sed -i '/rm/d' /usr/share/ubiquity/apt-setup
    sed -i '/boot/d' /usr/share/ubiquity/apt-setup
    sed -i '/cdrom:/d' /usr/share/ubiquity/apt-setup
    echo "mkdir -p /target/boot/efi" >> /usr/share/ubiquity/apt-setup
    echo "rm -f /target/boot/efi/startup.nsh" >> /usr/share/ubiquity/apt-setup
    echo "touch /target/boot/efi/startup.nsh" >> /usr/share/ubiquity/apt-setup
    ARCH=`archdetect | awk -F "/" '{print $1}'`
    if [ "$ARCH" = "amd64" ] ; then
    echo 'echo "fs0:\EFI\ubuntu\grubx64.efi" >> /target/boot/efi/startup.nsh' >> /usr/share/ubiquity/apt-setup
    else
    echo 'echo "fs0:\EFI\custom\grubia32.efi" >> /target/boot/efi/startup.nsh' >> /usr/share/ubiquity/apt-setup
    fi
    echo "rm -f /target/etc/gdm3/custom.conf" >> /usr/share/ubiquity/apt-setup
    echo "rm -f /target/etc/mdm/mdm.conf" >> /usr/share/ubiquity/apt-setup

    sleep 1

    #Creating startup script to set the installer as trusted
    #rm -rf /etc/systemd/system/rc.local.service
    #touch /etc/systemd/system/rc.local.service
    #echo "[Unit]" >> /etc/systemd/system/rc.local.service
    #echo "Description=/etc/rc.local Compatibility" >> /etc/systemd/system/rc.local.service
    #echo "ConditionPathExists=/etc/rc.local" >> /etc/systemd/system/rc.local.service
    #echo "[Service]" >> /etc/systemd/system/rc.local.service
    #echo "Type=forking" >> /etc/systemd/system/rc.local.service
    #echo "ExecStart=/etc/rc.local start" >> /etc/systemd/system/rc.local.service
    #echo "TimeoutSec=0" >> /etc/systemd/system/rc.local.service
    #echo "StandardOutput=tty" >> /etc/systemd/system/rc.local.service
    #echo "RemainAfterExit=yes" >> /etc/systemd/system/rc.local.service
    #echo "SysVStartPriority=99" >> /etc/systemd/system/rc.local.service
    #echo "[Install]" >> /etc/systemd/system/rc.local.service
    #echo "WantedBy=multi-user.target" >> /etc/systemd/system/rc.local.service
    #chmod 755 /etc/systemd/system/rc.local.service
    #chmod +x /etc/systemd/system/rc.local.service

    #sleep 1

    #systemctl enable rc.local.service
    #systemctl start rc.local.service

    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}
        mkdir -p $WORKDIR/dummysys/{dev,etc,proc,tmp,sys,mnt,media/cdrom,var}
        rsync -a /dev/urandom $WORKDIR/dummysys/dev/
        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
    ARCH=`archdetect | awk -F "/" '{print $1}'`
    DISKINFONAME=`echo $LIVECDLABEL | awk '{print $1}'`
    log_msg "Adding CD-ROM to source list"
    . /etc/lsb-release
    sed -i "s/deb/#deb/g" $WORKDIR/dummysys/etc/apt/sources.list
    sed -i '/cdrom:/d' $WORKDIR/dummysys/etc/apt/sources.list &> /dev/null
    echo "deb cdrom:[$DISKINFONAME $DISTRIB_RELEASE - Release $ARCH]/ dists/" >> $WORKDIR/dummysys/etc/apt/sources.list
    echo "deb http://archive.ubuntu.com/ubuntu bionic main restricted" >> $WORKDIR/dummysys/etc/apt/sources.list
    echo "deb http://archive.ubuntu.com/ubuntu bionic universe" >> $WORKDIR/dummysys/etc/apt/sources.list
    echo "deb http://archive.ubuntu.com/ubuntu bionic-backports main restricted universe multiverse" >> $WORKDIR/dummysys/etc/apt/sources.list
    echo "deb http://archive.canonical.com/ubuntu bionic partner" >> $WORKDIR/dummysys/etc/apt/sources.list
    echo "deb http://archive.ubuntu.com/ubuntu bionic-security main restricted" >> $WORKDIR/dummysys/etc/apt/sources.list
    echo "deb http://archive.ubuntu.com/ubuntu bionic-security universe" >> $WORKDIR/dummysys/etc/apt/sources.list
    echo "deb http://archive.ubuntu.com/ubuntu bionic-security multiverse" >> $WORKDIR/dummysys/etc/apt/sources.list

    #renaming grub config
    sed -i "s/GRUB_DISTRIBUTOR=.*/GRUB_DISTRIBUTOR=\"$LIVECDLABEL\"/g" $WORKDIR/dummysys/etc/default/grub
    chmod 777 $WORKDIR/dummysys/etc/lsb-release
    sed -i '/DISTRIB_DESCRIPTION/d' $WORKDIR/dummysys/etc/lsb-release &> /dev/null
    echo "DISTRIB_DESCRIPTION=\"$LIVECDLABEL\"" >> /home/PinguyBuilder/PinguyBuilder/dummysys/etc/lsb-release

    #Creating startup script so the installer is marked as 'Trusted' on the desktop
    touch $WORKDIR/dummysys/etc/rc.local
    echo "#!/bin/sh" >> $WORKDIR/dummysys/etc/rc.local
    echo "sudo -i -u $LIVEUSER dbus-run-session -- gio set /home/$LIVEUSER/Desktop/ubiquity.desktop metadata::trusted yes" >> $WORKDIR/dummysys/etc/rc.local
    echo "exit 0" >> $WORKDIR/dummysys/etc/rc.local
    chmod 755 $WORKDIR/dummysys/etc/rc.local
    chmod +x $WORKDIR/dummysys/etc/rc.local

    #Creating Network Update Script
    touch $WORKDIR/dummysys/etc/network/if-up.d/update
    echo "#!/bin/sh" >> $WORKDIR/dummysys/etc/network/if-up.d/update
    echo "apt-get update" >> $WORKDIR/dummysys/etc/network/if-up.d/update
    chmod 755 $WORKDIR/dummysys/etc/network/if-up.d/update
    chmod +x $WORKDIR/dummysys/etc/network/if-up.d/update

    log_msg "Cleaning up files not needed for the live in $WORKDIR/dummysys"
    rm -rf $WORKDIR/dummysys/etc/apt/sources.list.d/*.save &> /dev/null
    rm -rf $WORKDIR/dummysys/etc/apt/apt.conf.d/* &> /dev/null
    rm -rf $WORKDIR/dummysys/etc/apt/preferences.d/* &> /dev/null
    rm -rf $WORKDIR/dummysys/var/lib/apt/lists/* -vf &> /dev/null
    rm -rf $WORKDIR/dummysys/var/lib/apt/lists/lock &> /dev/null
    find $WORKDIR/dummysys/var/cache/apt -type f -exec rm -rf '{}' \; &> /dev/null
    find $WORKDIR/dummysys/var/cache/apt-xapian-index -type f -exec rm -rf '{}' \; &> /dev/null
    find $WORKDIR/dummysys/var/lib/apt -type f -exec rm -rf '{}' \; &> /dev/null
    rm -rf $WORKDIR/dummysys/var/lib/ureadahead/pack &> /dev/null
    rm -f $WORKDIR/dummysys/etc/X11/xorg.conf*
    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/ $WORKDIR/dummysys/var/lock/ $WORKDIR/dummysys/var/backups/ $WORKDIR/dummysys/var/tmp/ $WORKDIR/dummysys/var/crash/ $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/gdm3/*
        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/gdm3/gdm3.conf-custom
        rm -rf $WORKDIR/dummysys/etc/apt/sources.list.d/*
        cp -a /etc/PinguyBuilder/scripts/logo $WORKDIR/dummysys/etc/cron.hourly
        chmod +x $WORKDIR/dummysys/etc/cron.hourly/logo
        chmod 755 $WORKDIR/dummysys/etc/cron.hourly/logo
        #Setting up auto timed login for gdm3
        cp -a /etc/PinguyBuilder/gdm3 $WORKDIR/dummysys/etc/
        sed -i "s/LIVEUSER/$LIVEUSER/g" $WORKDIR/dummysys/etc/gdm3/custom.conf
        chmod +x $WORKDIR/dummysys/etc/gdm3/custom.conf
        chmod 755 $WORKDIR/dummysys/etc/gdm3/custom.conf
        #Setting up auto timed login for MDM
        cp -a /etc/PinguyBuilder/mdm $WORKDIR/dummysys/etc/
        sed -i "s/LIVEUSER/$LIVEUSER/g" $WORKDIR/dummysys/etc/mdm/mdm.conf
        chmod +x $WORKDIR/dummysys/etc/mdm/mdm.conf
        chmod 755 $WORKDIR/dummysys/etc/mdm/mdm.conf
        if [ ! -d /run ]; then
		find $WORKDIR/dummysys/var/run/ $WORKDIR/dummysys/var/mail/ $WORKDIR/dummysys/var/spool/ -type f -exec rm -f {} \;
	else
		find $WORKDIR/dummysys/var/mail/ $WORKDIR/dummysys/var/spool/ -type f -exec rm -f {} \;
		unlink $WORKDIR/dummysys/var/run
		cd $WORKDIR/dummysys/var
		ln -sf ../run run
	fi
        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
        #Add Liveuser to groups
        #sed -i "s/adm:x:4:/adm:x:4:$LIVEUSER,/g" $WORKDIR/dummysys/etc/group
        #sed -i "s/sudo:x:27:/sudo:x:27:$LIVEUSER,/g" $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 /usr/share/initramfs-tools/scripts/casper
    [ "$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 /usr/share/initramfs-tools/scripts/casper

    # copy over some of the necessary stuff for the livecd

    #copy any preseed files
    cp /etc/PinguyBuilder/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
    log_msg "Copying EFI Boot for the live system"
    cp -a /usr/lib/PinguyBuilder/boot $WORKDIR/ISOTMP/
    cp -a /usr/lib/PinguyBuilder/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

    #Downloading packages for offline install
    log_msg "Downloading packages for CD"
    
    # Check Architecture
    ARCH=`archdetect | awk -F "/" '{print $1}'`

    mkdir -p $WORKDIR/ISOTMP/pool
      cd $WORKDIR/ISOTMP/pool
    if [ "$ARCH" = "amd64" ] ; then
    apt-get download b43-fwcutter bcmwl-kernel-source efibootmgr grub-common grub-efi grub-efi-amd64 grub-efi-amd64-bin grub-efi-amd64-signed grub-efi-ia32 grub-efi-ia32-bin grub-pc-bin grub-pc grub2-common grub-gfxpayload-lists mokutil os-prober secureboot-db shim shim-signed &> /dev/null
    else
    apt-get download b43-fwcutter bcmwl-kernel-source efibootmgr grub-common grub-efi grub-efi-ia32 grub-efi-ia32-bin grub-pc-bin grub-pc grub2-common grub-gfxpayload-lists mokutil os-prober secureboot-db &> /dev/null
    fi
     mkdir -p $WORKDIR/ISOTMP/dists
     cd $WORKDIR/ISOTMP/
    dpkg-scanpackages pool /dev/null | gzip -9c > 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/PinguyBuilder/customisolinux/isolinux.cfg ]; then
        log_msg "Creating isolinux setup for the live system"
        find /usr -name 'isolinux.bin' -exec cp {} $WORKDIR/ISOTMP/isolinux/ \;
        #find fix for vesamenu.32 provided by Krasimir S. Stefanov <lokiisyourmaster@gmail.com>
        VESAMENU=`find /usr -print0 | grep -FzZ "bios/vesamenu.c32"`
        cp $VESAMENU $WORKDIR/ISOTMP/isolinux/ 
        LDLINUX=`find /usr -print0 | grep -FzZ "bios/ldlinux.c32"`
        cp $LDLINUX $WORKDIR/ISOTMP/isolinux/
        LIBUTIL=`find /usr -print0 | grep -FzZ "bios/libutil.c32"`
        cp $LIBUTIL $WORKDIR/ISOTMP/isolinux/
        LIBCOM=`find /usr -print0 | grep -FzZ "bios/libcom32.c32"`
        cp $LIBCOM $WORKDIR/ISOTMP/isolinux/
        MENU=`find /usr -print0 | grep -FzZ "bios/menu.c32"`
        cp $MENU $WORKDIR/ISOTMP/isolinux/
        # setup isolinux for the livecd
        VERSION=`lsb_release -r | awk '{print $2}' | awk -F "." '{print $1}'`
        sed -e 's/__LIVECDLABEL__/'"$LIVECDLABEL"'/g' /etc/PinguyBuilder/isolinux/isolinux.cfg.vesamenu > \
        $WORKDIR/ISOTMP/isolinux/isolinux.cfg
        cp /etc/PinguyBuilder/isolinux/splash.png $WORKDIR/ISOTMP/isolinux/splash.png
    else
        log_msg "Copying your custom isolinux setup to the live system"
        cp /etc/PinguyBuilder/customisolinux/* $WORKDIR/ISOTMP/isolinux/ &> /dev/null

    fi

    log_msg "Checking the ARCH of the system and setting the README.diskdefines file"
    ARCH=`archdetect | awk -F "/" '{print $1}'`

    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 folder 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/share/applications -name ubiquity*.desktop `
            install -d -o $LIVEUSER -g $LIVEUSER /$LIVEHOME/Desktop &> /dev/null
            install -D -o $LIVEUSER -g $LIVEUSER $UBIQUITYDESKTOP /$LIVEHOME/Desktop/ &> /dev/null
            sed -i "s/RELEASE/$LIVECDLABEL/" "/$LIVEHOME/Desktop/`basename $UBIQUITYDESKTOP`" &> /dev/null
            chmod +x "/$LIVEHOME/Desktop/`basename $UBIQUITYDESKTOP`"
            sudo -i -u $LIVEUSER dbus-run-session -- gio set "/$LIVEHOME/Desktop/`basename $UBIQUITYDESKTOP`" metadata::trusted yes
        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
    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=""

    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

    mksquashfs $REALFOLDERS $WORKDIR/ISOTMP/casper/filesystem.squashfs $SQUASHFSOPTS -e /boot/efi/EFI /boot/grub $BASEWORKDIR $EXCLUDES 2>>$WORKDIR/PinguyBuilder.log


    sleep 1

    #add some stuff the log in case of problems so I can troubleshoot it easier
    echo "Updating the PinguyBuilder.log"
    echo "------------------------------------------------------" >>$WORKDIR/PinguyBuilder.log
    echo "Mount information" >>$WORKDIR/PinguyBuilder.log
    mount >>$WORKDIR/PinguyBuilder.log
    echo "------------------------------------------------------" >>$WORKDIR/PinguyBuilder.log
    echo "Disk size information" >>$WORKDIR/PinguyBuilder.log
    df -h >>$WORKDIR/PinguyBuilder.log
    echo "------------------------------------------------------" >>$WORKDIR/PinguyBuilder.log
    echo "Casper Script info" >>$WORKDIR/PinguyBuilder.log
    ls -l /usr/share/initramfs-tools/scripts/casper-bottom/ >>$WORKDIR/PinguyBuilder.log
    echo "------------------------------------------------------" >>$WORKDIR/PinguyBuilder.log
    echo "/etc/PinguyBuilder.conf info" >>$WORKDIR/PinguyBuilder.log
    cat /etc/PinguyBuilder.conf >>$WORKDIR/PinguyBuilder.log
    echo "------------------------------------------------------" >>$WORKDIR/PinguyBuilder.log
    echo "/etc/casper.conf info" >>$WORKDIR/PinguyBuilder.log
    cat /etc/casper.conf >>$WORKDIR/PinguyBuilder.log
    echo "------------------------------------------------------" >>$WORKDIR/PinguyBuilder.log
    echo "/etc/passwd info" >>$WORKDIR/PinguyBuilder.log
    cat $WORKDIR/dummysys/etc/passwd >>$WORKDIR/PinguyBuilder.log
    echo "------------------------------------------------------" >>$WORKDIR/PinguyBuilder.log
    echo "/etc/group info" >>$WORKDIR/PinguyBuilder.log
    cat $WORKDIR/dummysys/etc/group >>$WORKDIR/PinguyBuilder.log
    echo "------------------------------------------------------" >>$WORKDIR/PinguyBuilder.log
    echo "/etc/X11/default-display-manager info" >>$WORKDIR/PinguyBuilder.log
    cat $WORKDIR/dummysys/etc/X11/default-display-manager >>$WORKDIR/PinguyBuilder.log
    echo "------------------------------------------------------" >>$WORKDIR/PinguyBuilder.log
    echo "/etc/skel info" >>$WORKDIR/PinguyBuilder.log
    find /etc/skel >>$WORKDIR/PinguyBuilder.log
    echo "------------------------------------------------------" >>$WORKDIR/PinguyBuilder.log
    echo "lsb-release info" >>$WORKDIR/PinguyBuilder.log
    cat $WORKDIR/dummysys/etc/lsb-release >>$WORKDIR/PinguyBuilder.log
    echo "------------------------------------------------------" >>$WORKDIR/PinguyBuilder.log
    echo "PinguyBuilder version info" >>$WORKDIR/PinguyBuilder.log
    cat $WORKDIR/dummysys/etc/PinguyBuilder/PinguyBuilder.version >>$WORKDIR/PinguyBuilder.log
    echo "------------------------------------------------------" >>$WORKDIR/PinguyBuilder.log
    echo "ISOTMP info" >>$WORKDIR/PinguyBuilder.log
    ls -Rl $WORKDIR/ISOTMP >>$WORKDIR/PinguyBuilder.log
    echo "------------------------------------------------------" >>$WORKDIR/PinguyBuilder.log
    echo "$WORKDIR/tmpusers info" >>$WORKDIR/PinguyBuilder.log
    cat $WORKDIR/tmpusers >>$WORKDIR/PinguyBuilder.log
    echo "------------------------------------------------------" >>$WORKDIR/PinguyBuilder.log
    echo "Command-line options = $@" >>$WORKDIR/PinguyBuilder.log
    echo "------------------------------------------------------" >>$WORKDIR/PinguyBuilder.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/*/*/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
    apt-get -y -q remove ubiquity-ubuntu-artwork &> /dev/null
    #apt-get --yes --assume-yes autoremove &> /dev/null
    rm -rf /root/apt.tar.gz
    apt-get install -y $(check-language-support) &> /dev/null

    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" -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 PinguyBuilder-firstboot from system startup"
    update-rc.d -f PinguyBuilder-firstboot remove
    chmod 644 /etc/init.d/PinguyBuilder-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 PinguyBuilder dist iso before sudo PinguyBuilder 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."
    . /etc/lsb-release
    touch $WORKDIR/ISOTMP/ubuntu
    touch $WORKDIR/ISOTMP/.disk/base_installable
    echo "full_cd/single" > $WORKDIR/ISOTMP/.disk/cd_type
    ARCH=`archdetect | awk -F "/" '{print $1}'`
    # starting with 12.04 need to have correct ubuntu version or startup disk creator uses syslinux-legacy which won't work
    DISKINFONAME=`echo $LIVECDLABEL | awk '{print $1}'`
    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"
    $CREATEISO -iso-level 3 -quiet -r -V "$LIVECDLABEL" -cache-inodes -J -l -b isolinux/isolinux.bin -c isolinux/boot.cat -no-emul-boot -boot-load-size 4 -boot-info-table -eltorito-alt-boot -e boot/grub/efi.img -no-emul-boot -o $WORKDIR/$CUSTOMISO "$WORKDIR/ISOTMP" 2>>$WORKDIR/PinguyBuilder.log 1>>$WORKDIR/PinguyBuilder.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.
    log_msg "Making $CUSTOMISO a hybrid iso"
    isohybrid --uefi $WORKDIR/$CUSTOMISO

    # 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 $CUSTOMISO.md5 in $WORKDIR"

    cd $WORKDIR
    md5sum $CUSTOMISO > $CUSTOMISO.md5

    sleep 1

    log_msg "Creating $CUSTOMISO.sha256 in $WORKDIR"

    cd $WORKDIR
    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 iso or cdfs options have been invoked and proceed accordingly

# Replaced this with a CASE statement, below
#~ if [ "$2" = "iso" ]; then
    #~ iso $@
#~ elif [ "$2" = "cdfs" ]; then
    #~ cdfs $@
#~ else
    #~ cdfs $@
    #~ iso $@
#~ fi

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




exit 0
