#!/bin/bash

# SugarClone installs a copy of a Sugar on a Stick image on a second device.
# The source may be the running image, another installed partition, or an .iso
# file. SugarClone is available at http://people.sugarlabs.org/fgrose
#
# Copyright 2010, Sugar Labs
# Frederick Grose <fgrose@sugarlabs.org>

# Requires: 'modified_livecd-iso-to-disk'
# http://people.sugarlabs.org/fgrose
# which is based on 'livecd-iso-to-disk'
# http://git.fedorahosted.org/git/livecd/tools?p=livecd;a=tree;f=tools;hb=HEAD
# to load a live media .iso image or the running live image onto a bootable,
# flash storage device.
# 
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

export PATH=/sbin:/usr/sbin:$PATH

shortusage() {
    brief='
    Short usage information for this program follows:
    
    NAME 

    SugarClone  -  Installs a copy of a Sugar image on a second device.
    
    SYNTAX
    
       Simplest:
       
           SugarClone

       Simple:
       
           SugarClone [--help] [--skipcopy] [--image <source>] [--mntpnt <wdir>]
                      [--builder <name>]  [--keepuser] [quit]

       Extended:
       
           SugarClone [--format] [--reset-mbr] [--efi]
                      [--extra-kernel-args <args>] [--multi] [--livedir <dir>]
                      [--compress] [--skipcompress] [--swap-size-mb <size>]
                      [--xo] [--xo-no-home] [--noverify] [--skipcopy]
                      [--overlay-size-mb <size>] [--copy-overlay]
                      [--home-size-mb <size>] [--delete-home] [--copy-home]
                      [--force] [--crypted-home] [--unencrypted-home] [--help]
                      [--image <source>] [--mntpnt <wdir>] [--builder <name>]
                      [--skipcopy] [--keepuser] [quit]

    USAGE

    The script may be run in Simplest form with no command-line options.
    This will simply create a SugarClone of the running image.
        (The --noverify --copy-overlay --delete-home --copy-home options have
        been hard-coded into this mode.)
        
    If there is more than one USB storage device connected to your system,
    you will be presented with a menu to select the device you would like to
    make the target for the SugarClone.

    In the Simple mode, any of the --help --image <source> --mntpnt <wdir>
    --builder <name> --skipcopy, & --keepuser options may be entered to augment
    the Simplest mode.

    Extended mode allows one to override the default options.
    Enter any one of the available options before any from the Simple set.
    If --help is entered, this usage document will be displayed.

    REQUIRES

    modified_livecd-iso-to-disk - also available at
                                  http://people.sugarlabs.org/fgrose
                                    
    Enter SugarClone --help on the command line to see more information.
'
}
shortusage

usage() {
    echo -e "
    ""$brief"
    echo "
    DESCRIPTION

    SugarClone installs a Live CD/DVD/USB/SD image (LiveOS) onto a USB/SD
    storage device.  The USB/SD storage device can then boot the installed
    operating system on systems that support booting via USB/SD.  SugarClone
    requires a LiveOS .iso image file, or a currently running LiveOS image or an
    installed image mount point, and a target USB/SD storage device.  If the
    operating system supports persistent overlays to save system changes, a
    fresh overlay, or a copy of the currently running overlay may be included in
    the installation.  This enables one to easily prepare customized LiveOS
    images for redistribution.

    Unless you request the --format or --reset-mbr options, the installation
    does not destroy data outside of the LiveOS, syslinux, EFI, & boot folders
    on your target device.  This allows one to maintain other files on the
    USB/SD disk outside of the LiveOS filesystem.

    LiveOS images provide embedded filesystems through the Device-mapper
    component of the Linux kernel.  The embedded filesystems exist within files
    such as /LiveOS/squashfs.img or /LiveOS/ext3fs.img on the primary volume
    partition of the storage device.  In use, these are read-only filesystems.
    Optionally, one may specify a persistent home folder, which will exist in a
    /LiveOS/home.img filesystem image file.  Persistent LiveOS overlays hold
    image change snapshots in the /LiveOS/overlay-<device_id> file.

    Customized SugarClones are made by copying the source image filesystems to
    the bootable primary volume partition of another USB/SD device and adjusting
    the syslinux boot configuration and overlay files to reflect the new device
    identification.  The Sugar learner's Journal account identification keys,
    /home/liveuser/.sugar/default/owner.key & owner.key.pub are excluded from
    the copy so when the new SugarClone is booted, the learner will be asked to
    establish a new identification.  The original learner's Journal is copied
    into the new SugarClone and bears the original learner's color signature.
        (The original ownership keys may be maintained in the new SugarClone by
        submitting the --keepuser option on the command line.  This is a way to
        backup or archive the entire LiveOS image, including operating system
        changes.)    

    OPTIONS

    --image <source>   (default: /dev/live)
        The running live image device , another partition
        holding a live image, or the path to an .iso file bearing a live image.

    --builder <name>  
        The name of the builder of the customized SugarClone. Default: someone

    --mntpnt <wdir>   (default: /mnt/live)
        The filesystem directory mount point for the source holding the build
        scripts, SugarClone and modified_livecd-iso-to-disk.

    --help
        Displays usage information and exits.
            
    quit
        Interrupts interactive dialog and exits.
        
    --format
        Formats the USB/SD stick and creates an MS-DOS partition table (or GPT 
        partition table if --efi is passed).
        
    --reset-mbr
        Sets the Master Boot Record(MBR) of the USB/SD storage device to the 
        mbr.bin file from the image's syslinux directory.
        
    --efi
        Creates a GPT partition table when --format is passed, and install a 
        hybrid EFI/MBR bootloader on the disk.  This is necessary for most Intel
        Macs.
        
    --extra-kernel-args <args>
        Specifies additional kernel arguments, <args>, that will be inserted
        into the syslinux and EFI boot configurations.  Multiple arguments
        should be specified in one string, i.e.,
            --extra-kernel-args \"arg1 arg2 ...\"
        
    --multi
        Used when enabling multi image copies (avoiding configuration of the
        boot files for an arbitrary image).
        
    --livedir <dir>
        Used with multi image copies to designate the directory <dir> for the
        particular image.
        
    --compress   (default option)
        Installs image on a compressed SquashFS filesystem.
        
    --skipcompress   (default for when option --xo is specified)
        Installs the operation system into the /LiveOS/ext3fs.img filesystem
        image file.
        
    --xo
        Used to prepare an image for the OLPC XO laptop and its compressed JFFS2 
        filesystem.  Do not use the following options with --xo: 
            --overlay-size-mb <size>, home-size-mb <size>, --delete-home, 
            --copy-home, --copy-overlay, --compress
        
    --xo-no-home
        Used together with the --xo option to prepare an image for an OLPC XO 
        laptop with the home folder on an SD card instead of the internal NAND
        flash storage.
        
    --noverify   (default)
        Disables the image validation process which occurs before the image is 
        installed.  When this option is enabled, the image is not verified
        before loading onto the USB/SD storage device.
        
    --skipcopy
        Skips the copy of the live image to the USB/SD device.  (Used to repair
        disk configuration files or while testing the script in order to avoid
        repeated and lengthy copy commands.)
        
    --overlay-size-mb <size>
        This option specifies the creation of a persistent overlay and sets its 
        <size> in MB.  The overlay is additional storage available to the live
        operating system if the operating system supports it.  The USB/SD
        storage device must have enough free space for the image and the
        overlay.  The overlay holds image change snapshots in the
        /LiveOS/overlay-<device_id> file.  There is a maximum <size> of 2047 MB
        for vfat formatted devices.  If there is insufficient room on your
        device, you will be given information to adjust your settings.
        
    --copy-overlay   (default)
        This option allows one to copy a persistent overlay from a running 
        live image to the new SugarClone.  Changes already made in the running 
        image will be propagated to the new installation.  
        WARNING: User sensitive information such as password cookies and 
        activity histories will be copied to the new installation!  Scrub this 
        information before using this option.
        
    --delete-home   (default)
        Must be explicitly selected when options --home-size-mb <size> or 
        --copy-home are selected and there is an existing persistent home
        directory on the image.
        
    --home-size-mb <size>
        Specifies creation of a persistent home directory and sets its size in 
        megabytes.  Note that --delete-home must also be selected to replace an 
        existing persistent home with a new, empty one.  The directory is saved
        in the /LiveOS/home.img file.  There is a maximum <size> of 2047 MB for
        vfat formatted devices.  If there is insufficient room on your device,
        you will be given information to adjust your settings.
        
    --copy-home   (default)
        This option allows one to copy a persistent home folder from a running 
        live image to the new SugarClone.  Changes already made in the running 
        image home directory will be propagated to the new installation.  
        WARNING: User sensitive information such as password cookies and 
        activity histories will be copied to the new installation! Scrub this 
        information before using this option.

    --keepuser
        Specifies that the Sugar learner's Journal identification keys should be
        preserved (copied into) the new SugarClone.  This feature can be used to
        backup or archive the full image in the new LiveOS storage device.
        
    --force
        This option allows one to bypass the user confirmation for deletion of 
        an existing home directory on the target device, if one exists.
        
    --crypted-home   (default, if home-size-mb is specified)
        Encrypts a persistent home directory.
        
    --unencrypted-home
        Disables the encryption of the persistent home directory.

    CONTRIBUTORS

    SugarClone: Frederick Grose, Thomas Gilliard, and others.

    livecd-iso-to-disk: David Zeuthen, Jeremy Katz, Douglas McClendon,
                        Chris Curranm and other contributors.
                        (See the AUTHORS file in the source distribution for
                        the complete list of credits.)

    BUGS

    Report bugs to the mailing list
    http://lists.sugarlabs.org/mailman/listinfo/soas or directly to
    http://bugs.sugarlabs.org against the soas component.

    COPYRIGHT

    Copyright (C) Sugar Labs 2010 and various contributors. This is free
    software. You may redistribute copies of it under the terms of the
    GNU General Public License, http://www.gnu.org/licenses/gpl.html.
    There is NO WARRANTY, to the extent permitted by law.

    SEE ALSO

    livecd-creator, project website http://fedoraproject.org/wiki/FedoraLiveCD
    "
    exit 1
}

cleanup() {
    sleep 2
    su --session-command="[ -d "$TARGETMNT" ] && \
    ( umount $TARGETMNT &> /dev/null && rmdir $TARGETMNT &> /dev/null )" root
    su --session-command="rmdir -v /media/target.* &> /dev/null" root
}

exitclean() {
    echo "Cleaning up to exit..."
    cleanup
    [ -z $keepuser ] && restorekeys
    exit 1
}

restorekeys() {
    [ -f /mnt/live/owner.key ] && mv /mnt/live/owner.key /home/liveuser/.sugar/default/owner.key
    [ -f /mnt/live/owner.key.pub ] && mv /mnt/live/owner.key.pub /home/liveuser/.sugar/default/owner.key.pub
#    chown liveuser:liveuser /home/liveuser/.sugar/default/owner.key /home/liveuser/.sugar/default/owner.key.pub
#    chmod 600 /home/liveuser/.sugar/default/owner.key
#    chmod 644 /home/liveuser/.sugar/default/owner.key.pub
    sync
}

checkint() {
    if ! test $2 -gt 0 2>/dev/null ; then
        echo -e "\a $1 $2 $baditem"
        see[1]="--> ERROR: You must specify a $1 <size> value; $2 is invalid.\n\n"
        see[2]="${see[2]}\r --> You entered INVALID option/argument(s):"
        baditem="$baditem $2"
        see[3]="$baditem"
        return 1
    fi
}

declare -a liveArgs
declare -a cloneArgs
declare -a see
baditem=

cryptedhome=1
keephome=1
homesizemb=0
copyhomesize=0
swapsizemb=0
overlaysizemb=0
copyoverlay=1
copyhome=1
keepuser=""
isotype=
LIVEOS=LiveOS
HOMEFILE="home.img"
builder=someone
SOURCEMNT=/mnt/live
SOURCE=/dev/live

processArgs() {
    squigleline="≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈\
    \b\b\b\b≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈"
    
    until [ $# -eq 0 ]; do
        case $1 in
        --image)
            SOURCE=$(readlink -f "$2")
            if ! [ -b "$SOURCE" -o -s "$SOURCE" -o -d "$SOURCE" ]; then
                see[1]="--> $SOURCE is not a valid source image.
                Please adjust this command requirement.\n\n"
                baditem="$baditem $2"
                see[3]="$baditem"               
            else
                cloneArgs[0]="$1"
                cloneArgs[1]="$2"
            fi
            shift
            ;;
        x--image)
            SOURCE=/dev/live
            if ! [ -b "$SOURCE" ]; then
                see[1]=" --> The default image source, $SOURCE, is invalid here.
                Please adjust this command requirement.\n\n"
                baditem="$baditem $SOURCE"
                see[3]="$baditem"
            else
                cloneArgs[0]=
                cloneArgs[1]=
            fi
            ;;
        --mntpnt)
            SOURCEMNT=$2
            cloneArgs[2]="$1"
            cloneArgs[3]="$2"
            shift ;;
        x--mntpnt)
            SOURCEMNT=/mnt/live
            cloneArgs[2]=
            cloneArgs[3]=
            ;;
        --builder)
            builder=$2
            cloneArgs[4]="$1"
            cloneArgs[5]="$2"
            shift ;;
        x--builder)
            builder=someone
            cloneArgs[4]=
            cloneArgs[5]=
            ;;
        --help)
            usage #| less
            ;;
        quit)
            exit 1
            ;;             
        --format)
            format=1
            liveArgs[0]="$1" ;;
        x--format)
            format= ; liveArgs[0]=
            ;;
        --reset-mbr|--resetmbr)
            resetmbr=1
            liveArgs[1]="$1" ;;
        x--reset-mbr|x--resetmbr)
            resetmbr= ; liveArgs[1]=
            ;;
        --efi|--mactel)
            efi=1
            liveArgs[2]="$1" ;;
        x--efi|x--mactel)
            efi= ; liveArgs[2]=
            ;;
        --extra-kernel-args)
            kernelargs=$2
            liveArgs[3]="$1"
            liveArgs[4]="$2"
            shift
            ;;
        x--extra-kernel-args)
            kernelargs= ; liveArgs[3]= ; liveArgs[4]=
            ;;
        --multi)
            multi=1
            liveArgs[5]="$1" ;;
        x--multi)
            multi= ; liveArgs[5]=
            ;;
        --livedir)
            LIVEOS=$2
            liveArgs[6]="$1"
            liveArgs[7]="$2"
            shift ;;
        x--livedir)
            LIVEOS= ; liveArgs[6]= ; liveArgs[7]=
            ;;
        --compress)
            skipcompress=""
            liveArgs[8]="$1" ;;
        x--compress)
            skipcompress=1 ; liveArgs[8]=
            ;;
        --skipcompress)
            skipcompress=1
            liveArgs[9]="$1" ;;
        x--skipcompress)
            skipcompress= ; liveArgs[9]=
            ;;
        --swap-size-mb)
            checkint $1 $2
            if [ $? -eq 0 ]; then
                swapsizemb=$2
                liveArgs[10]="$1"
                liveArgs[11]="$2"
            fi
            shift ;;
        x--swap-size-mb)
            swapsizemb= ; liveArgs[10]= ; liveArgs[11]=
            ;;
        --xo)
            xo=1
            skipcompress=1
            liveArgs[12]="$1" ;;
        x--xo)
            xo= ; skipcompress= ; liveArgs[12]=
            ;;
        --xo-no-home)
            xonohome=1
            liveArgs[13]="$1" ;;
        x--xo-no-home)
            xonohome= ; liveArgs[13]=
            ;;
        --noverify)
            noverify=1
            liveArgs[14]="$1" ;;
        x--noverify)
            noverify= ; liveArgs[14]=
            ;;
        --skipcopy)
            skipcopy=1
            liveArgs[15]="$1" ;;
        x--skipcopy)
            skipcopy= ; liveArgs[15]=
            ;;
        --overlay-size-mb)
            checkint $1 $2
            if [ $? -eq 0 ]; then
                overlaysizemb=$2
                liveArgs[16]="$1"
                liveArgs[17]="$2"
            fi
            shift ;;
        x--overlay-size-mb)
            overlaysizemb= ; liveArgs[16]= ; liveArgs[17]=
            ;;
        --copy-overlay)
            copyoverlay="1"
            liveArgs[18]="$1" ;;
        x--copy-overlay)
            copyoverlay= ; liveArgs[18]=
            ;;
        --delete-home)
            keephome=""
            liveArgs[19]="$1" ;;
        x--delete-home)
            keephome=1 ; liveArgs[19]=
            ;;
        --home-size-mb)
            checkint $1 $2
            if [ $? -eq 0 ]; then
                homesizemb=$2
                liveArgs[20]="$1"
                liveArgs[21]="$2"
            fi
            shift ;;
        x--home-size-mb)
            homesizemb= ; liveArgs[20]= ; liveArgs[21]=
            ;;
        --copy-home)
            copyhome="1"
            liveArgs[22]="$1" ;;
        x--copy-home)
            copyhome= ; liveArgs[22]=
            ;;
        --keepuser)
            keepuser="1" ;;
        x--keepuser)
            keepuser=
            ;;
        --force)
            force=1
            liveArgs[23]="$1" ;;
        x--force)
            force= ; liveArgs[23]=
            ;;
        --crypted-home)
            cryptedhome=1
            liveArgs[24]="$1" ;;
        x--crypted-home)
            cryptedhome= ; liveArgs[24]=
            ;;
        --unencrypted-home)
           	cryptedhome=""
           	liveArgs[25]="$1" ;;
        x--unencrypted-home)
            cryptedhome=1 ; liveArgs[25]=
            ;;
        *)
            see[2]="${see[2]}\r --> You entered INVALID option/argument(s):"
            baditem="$baditem $1"
            see[3]="$baditem"
            ;;
        esac
        if [ -z "$baditem" ]; then       
            echo -en "\a $baditem"
        fi
        shift
    done
    if [ -n "$baditem" ]; then
        see[0]="$brief$squigleline\n
           --> (Scroll up, if needed, to see usage information.) <--\n\n"
        see[4]="\n\n        Please try again.\n
     These options/arguments are acceptable: ${cloneArgs[*]}  ${liveArgs[*]}"
        see[5]="\n
 --> Please Enter replacements for just the baditem option/argument(s), OR\n
     just press 'Enter' to ignore those.\n
     (You may Enter additional option/arguments, OR override any by
     entering that option with an 'x' prefix, such as this: x--skipcopy.)
        To exit altogether, Enter: quit\n"
        echo -e "${see[*]}"
        read -p " --> Go ahead here: " -a inputArgs
        clear
        baditem=
        see[1]=
        [ -n "${inputArgs[*]}" ] && processArgs "${inputArgs[@]}"
    fi
}

declare -a inputArgs
defaultArgs="--noverify --copy-overlay --delete-home --copy-home"
if [ $# -eq 0 ]; then
    set -- $defaultArgs
    processArgs $@
else
    case "$1" in
    --skipcopy|--image|--mntpnt|--builder|--keepuser|--help|--quit)
        inputArgs=( "$*" )
        processArgs $@
        set -- $defaultArgs
        processArgs $@
        ;;
    *)
        processArgs $@
        ;;
    esac
fi
echo -e "cloneArgs: ${cloneArgs[*]}\nliveArgs: ${liveArgs[*]}"


findStorageDevices() {
    declare -i i=0
    declare -i media_size
    declare -i size

    for udi in $(/usr/bin/hal-find-by-capability --capability storage)
    do
        device=$(hal-get-property --udi $udi --key block.device)
        vendor=$(hal-get-property --udi $udi --key storage.vendor)
        model=$(hal-get-property --udi $udi --key storage.model)
        bus=$(hal-get-property --udi $udi --key storage.bus)
        if [[ $bus == "usb" || $bus == "mmc" ]]
        then
            parent_udi=$(hal-find-by-property --key block.storage_device --string $udi)
            mount=$(hal-get-property --udi $parent_udi --key volume.mount_point)
            label=$(hal-get-property --udi $parent_udi --key volume.label)
            media_size=$(hal-get-property --udi $udi --key storage.removable.media_size)
            size=$((media_size/(1000*1000*1000)))
            if [[ "$mount" = /mnt/live ]]; then
                echo "This Live USB/SD device was detected."
            else
                USB_SDdevices+="$bus..$vendor..$model..$device..$mount..$label..$size-GB "
                USB_SDdev[$i]=$device
                ((i++))
            fi
        fi       
    done
    USB_SDdevices+="EXIT"
}

selectDevice() {
    findStorageDevices
    
    case ${#USB_SDdev[*]} in
    0)
        echo -e "\n   No USB/SD storage devices were detected on your system.\n
        \r   Please check that a device is inserted properly.\n   Exiting..."
        exit ;;
    1)
        TARGETDEV=$USB_SDdev
        echo -e "\n   One USB/SD storage device was detected:\n\n      ${USB_SDdevices}
        \n\r      That's where we'll load the SugarClone.\n      $USB_SDdev \n" ;;
    *)
        prompt="\n   Choose the USB/SD storage device to be loaded with the \
        \b\b\b\b\b\b\b\bSugarClone:\n\n   > "
        PS3=$(echo -en "$prompt")
        echo -e "\n   The following USB/SD devices were detected:\n"
        select TARGETDEV in $USB_SDdevices
        do
            case $TARGETDEV in
            "EXIT")
                echo -e "\n   OK, we will exit.\n"
                exit ;;
            "")
                echo -e "   Invalid entry.\r\a"
                continue ;;
            *)
                ;;
            esac 
            echo -e "   You chose: $TARGETDEV\n\n   choice # $REPLY, ${USB_SDdev[REPLY-1]}\n"
            TARGETDEV=${USB_SDdev[REPLY-1]}
            break
        done
    esac  
}

selectDevice

if [ -z $keepuser ]; then
    [ -f /home/liveuser/.sugar/default/owner.key ] && mv /home/liveuser/.sugar/default/owner.key /mnt/live/owner.key
    [ -f /home/liveuser/.sugar/default/owner.key.pub ] && mv /home/liveuser/.sugar/default/owner.key.pub /mnt/live/owner.key.pub
fi

TARGETMNT=$(su --session-command="mktemp -d /media/target.XXXXXX" root)
# FIXME: assumes partition 1 on TARGETDEV...
su --session-command="mount ${TARGETDEV}1 $TARGETMNT" root || \
    (echo -e "\n   PROBLEM: Unable to connect to the filesystem on the USB/SD device:
            $TARGETDEV\n    Exiting..." ; exitclean)

THISSCRIPT=$(readlink -f $0)
su --session-command="cp -f $THISSCRIPT $TARGETMNT/SugarClone" root

# adjust syslinux config directory for replication of installed images between filesystem types
checkSyslinuxVersion() {
# FIXME: Assuming no $multi, running on a live image
    multi=""
    LIVEOS=LiveOS
    
    if [ ! -x /usr/bin/syslinux ]; then
        echo "You need to have syslinux installed to run this script"
        exit 1
    fi
    if ! syslinux 2>&1 | grep -qe -d; then
        SYSLINUXPATH=""
    elif [ -n "$multi" ]; then
        SYSLINUXPATH="$LIVEOS/syslinux"
    else
        SYSLINUXPATH="syslinux"
    fi
}
checkSyslinuxVersion

# adjust syslinux sources for replication of installed images between filesystem types
if [ -d $SOURCEMNT/isolinux/ ]; then                    # CD or .iso file source
    return 1
elif [ -d $SOURCEMNT/$SYSLINUXPATH/ ]; then
    if [ -f $SOURCEMNT/$SYSLINUXPATH/extlinux.conf ]; then
        BOOTCONFIG=$SOURCEMNT/$SYSLINUXPATH/extlinux.conf
    elif [ -f $SOURCEMNT/$SYSLINUXPATH/syslinux.cfg ]; then
        BOOTCONFIG=$SOURCEMNT/$SYSLINUXPATH/syslinux.cfg
    fi
fi

# Set this to nothing so sed doesn't care
BOOTCONFIG_EFI=
if [ -n "$efi" ];then
    # this is a little ugly, but it gets the "interesting" named config file
    BOOTCONFIG_EFI=$SOURCEMNT/EFI/boot/boot?*.conf
# FIXME: needed?    rm -f $USBMNT/EFI/boot/grub.conf
fi

if ( [ -n "$BOOTCONFIG" ] && [ -n "$copyhome" -o -n "$copyoverlay" ] ); then
    echo "Updating boot config file"
    # FIXME: adjust menu title / release title fragile to changes in Welcome
    # message and EFI format
    existingTitle=$(grep "menu title" $BOOTCONFIG | awk {'print $5;'})
    existingTitle=${existingTitle%!}
    cloneDate=$(date '+%d %b %Y')
    
    sed -i -e "s/title Welcome to .*/title Welcome to $existingTitle in a \
SugarClone prepared by $builder on ${cloneDate}!/" $BOOTCONFIG $BOOTCONFIG_EFI

    releaseTitle="\
       remix of $existingTitle in a SugarClone prepared by $builder on $cloneDate"
    releaseName=/etc/fedora-release
    if [ -f "$releaseName" ]; then
        su --session-command="echo '$releaseTitle' >> $releaseName" root
    fi
fi
sync

cleanup
su --session-command="umount ${TARGETDEV}1 &> /dev/null" root

sync

#read -p "Pause..."

echo "${liveArgs[*]}"


(su --session-command="${SOURCEMNT}/modified_livecd-iso-to-disk ${liveArgs[*]} $SOURCE ${TARGETDEV}1" root)

if [ $? -eq 0 ]; then
    echo -e "Success! Your Sugar image is ready.\n"
else
   echo -e "\n   PROBLEM: Transfer of SugarClone failed.\n
   Exit code $? was reported.  Exiting...\n"
   exitclean
fi
