#!/bin/sh

if [ $# -lt 3 ]
then
    echo USAGE: $0 diskimage file directory
    exit 1
fi

DISKIMAGE="$1"
shift

FILE="$1"
shift

DISKIMAGEDEST="$1"
shift

COPYDIRS=$*

PROGRAM=`basename "$FILE"`
TMPDIR=/tmp/a2gs_mount.$$
MOUNTDIR="${TMPDIR}/$PROGRAM"
TMPDISKIMAGE=/tmp/a2gs_diskimage_$$.2mg
TMPARCHIVE=/tmp/s2gs_archive_$$.shk
TEMPLATEDISKIMAGE="make/${PROGRAM}.2mg"
ARCHIVE=`dirname "$DISKIMAGE"`/"${PROGRAM}.shk"
DEST="${MOUNTDIR}/${DISKIMAGEDEST}"

cleanupAndExit()
{
    umount "$MOUNTDIR" 2> /dev/null
    rm -f "$TMPDISKIMAGE" 2> /dev/null
    rm -f "$DISKIMAGE" 2> /dev/null
    rmdir "$MOUNTDIR" 2> /dev/null
    exit 1
}

if [ ! -f "$TEMPLATEDISKIMAGE" ]
then
    echo Unable to find the template disk image, $TEMPLATEDISKIMAGE
    cleanupAndExit
fi

cp "$TEMPLATEDISKIMAGE" "$TMPDISKIMAGE"
if [ $? != 0 ]
then
    echo Unable to copy template disk image.
    cleanupAndExit
fi

mkdir "$TMPDIR"
mkdir "$MOUNTDIR"
if [ $? != 0 ]
then
    echo Unable to create the mount directory.
    cleanupAndExit
fi

profuse -orw "$TMPDISKIMAGE" "$MOUNTDIR"
if [ $? != 0 ]
then
    echo Unable to mount the disk image.
    cleanupAndExit
fi

cp "$FILE" "$DEST"
if [ $? != 0 ]
then
    echo Unable to copy the file to the disk image.
    cleanupAndExit
fi

OLDDIR=`pwd`
for COPYDIR in $COPYDIRS
do
    cd "$COPYDIR"
    if [ $? != 0 ]
    then
        echo Unable to find $COPYDIR
        cleanupAndExit
    fi

    find . -print | while read FILEORDIR
    do
        if [ -d "$FILEORDIR" ]
        then
            mkdir -p "${MOUNTDIR}/$FILEORDIR"
        elif [ -f "$FILEORDIR" ]
        then
            cp "$FILEORDIR" "${MOUNTDIR}/$FILEORDIR"
        fi
    done
done

cd "$TMPDIR"
$ORCA "$OLDDIR/make/tar" cf "$TMPARCHIVE" "$PROGRAM"
if [ $? != 0 ]
then
    echo Unable to create archive.
    cleanupAndExit
fi
cd "$OLDDIR"

RETRIES=0
while [ $RETRIES -lt 5 ]
do
    umount "$MOUNTDIR"
    if [ $? -eq 0 ]
    then
        break
    fi

    RETRIES=`expr $RETRIES + 1`
    sleep 1
done

if [ $RETRIES -ge 5 ]
then
    echo Unable to unmount the disk image.
    cleanupAndExit
fi

cp "$TMPDISKIMAGE" "$DISKIMAGE"
if [ $? != 0 ]
then
    echo Unable to copy the disk image to the destination.
    cleanupAndExit
fi

cp "$TMPARCHIVE" "$ARCHIVE"
if [ $? != 0 ]
then
    echo Unable to copy the archive to the destination.
    cleanupAndExit
fi

# This is a special case for my personal build environment.  If I can find my home directory
# and the Sites directory in it, then also put a copy of the build there also.  This makes it
# available over http to my real GS so I can test it there also.
if [ -d /Users/jrand/Sites ]
then
    cp "$TMPDISKIMAGE" "/Users/jrand/Sites/$PROGRAM.2mg"
    cp "$TMPARCHIVE" "/Users/jrand/Sites/$PROGRAM.shk"
fi

rm -f "$TMPDISKIMAGE"
rm -f "$TMPARCHIVE"
rm -rf "$TMPDIR"
exit 0
