#!/bin/sh
#
# Copyright (c) 1999 University of Utah and the Flux Group.
# All rights reserved.
# 
# This file is part of the Flux OSKit.  The OSKit is free software, also known
# as "open source;" you can redistribute it and/or modify it under the terms
# of the GNU General Public License (GPL), version 2, as published by the Free
# Software Foundation (FSF).  To explore alternate licensing terms, contact
# the University of Utah at csl-dist@cs.utah.edu or +1-801-585-3271.
# 
# The OSKit 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 GPL for more details.  You should have
# received a copy of the GPL along with the OSKit; see the file COPYING.  If
# not, write to the FSF, 59 Temple Place #330, Boston, MA 02111-1307, USA.
#

#
# This script uses mtools to modify a preexisting MS-DOS 1.44MB floppy image
# to insert files on it.  The intent is to use a pre-fab bootable image
# (e.g. containing GRUB), and add files its boot loader will look for.
#

#
# Usage: mkdosfloppy -img ORIGINAL-IMAGE -o OUTPUT-IMAGE [-label LABEL]
#		     FILE[:DOSNAME]...
#
# The IMAGE file names may end in .gz if gzip'd.
#

while [ $# -gt 0 ]; do

	case "$1" in
	-img) oldimage="$2"; shift; shift ;;
	-o) newimage="$2"; shift; shift ;;
	-label) label="$2"; shift; shift ;;
	*) break ;;
	esac

done

mtools_conf=mtools.conf$$
tmpimage=floppy.img$$
trap 'rm -f $mtools_conf $tmpimage' 0 1 2 15

set -e

echo "drive x: file=\"`pwd`/$tmpimage\" 1.44m mformat_only" > $mtools_conf
MTOOLSRC=$mtools_conf
export MTOOLSRC

case $oldimage in
*.gz) gunzip -c $oldimage > $tmpimage ;;
*) cp $oldimage $tmpimage ;;
esac

test "x$label" = x || echo "$label" | mlabel x: >/dev/null 2>&1

for module in "$@"; do
	# Split out the associated string, if any.
	file="`echo $module | sed -e 's,:.*$,,'`"
	string="`echo $module | sed -e 's,^[^:]*:,,'`"
	test -n "$string" || string="$file"

	to="$string" from="$file"

	case "$to" in
	/*) ;;
	*) to="/$to" ;;
	esac

	mdel "x:$to" 2>/dev/null || true
	mcopy "$from" "x:$to"
done

kb=`mdu x: | awk '$1 == "X:/" { print ($2 / 2) }'`
echo "Your floppy has ${kb} kilobytes of file data."

case $newimage in
*.gz) gzip -9v < $tmpimage > $newimage ;;
*) mv -f $tmpimage $newimage ;;
esac

exit 0
