#!/bin/bash -x

# Installs a copy of a live Sugar on a Stick image on a second device.
#
# Copyright 2010, Sugar Labs
# Frederick Grose <fgrose@sugarlabs.org>

# Requires: 'livecd-iso-to-disk'
# from http://git.fedorahosted.org/git/livecd/tools?p=livecd;a=tree;f=tools;hb=HEAD
# to install a live media iso or running image so that
# it's bootable off of 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

cleanup() {
    sleep 2
    [ -d "$TARGETMNT" ] && ( umount $TARGETMNT && rmdir $TARGETMNT )
    rmdir -v /media/target.*
    restorekeys
}

exitclean() {
    echo "Cleaning up to exit..."
    cleanup
    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
}

[ -f /home/liveuser/.sugar/default/owner.key ] && chown root:root /home/liveuser/.sugar/default/owner.key
[ -f /home/liveuser/.sugar/default/owner.key.pub ] && chown root:root /home/liveuser/.sugar/default/owner.key.pub
[ -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

TARGETDEV=/dev/sdc1
TARGETMNT=$(mktemp -d /media/target.XXXXXX)
mount $TARGETDEV $TARGETMNT || exitclean

THISSCRIPT=$(readlink -f $0)
cp -f $THISSCRIPT $TARGETMNT/transferSugarImage
cp -f /mnt/live/newSugarStick $TARGETMNT/newSugarStick

sync

umount $TARGETMNT && rmdir $TARGETMNT
umount $TARGETDEV

sync

/mnt/live/modified_livecd-iso-to-disk --noverify --copy-overlay --delete-home --copy-home /dev/live $TARGETDEV || exitclean

echo "Success! Your Sugar image is ready."
exitclean
