#!/bin/sh

############################################################################
# This is SAR-make, the shell script itself. Don't hack around in this.
# If you're using it for the first time, just run it: it will create a file
# SAR-make.rc (from SAR-make.rc.default) with configurable settings.
# Once you hack around in SAR-make.rc, run this script again for the real
# thing.
############################################################################

resourcefile ()
{
    RC=$1.rc
    if [ ! -f $RC.default ] ; then
	error "Default resource $RC.default not found! " \
	      "Incomplete installation!"
    fi
    
    if [ -f $RC -a $RC -nt $RC.default ] ; then
	msg ''
	msg "Resource file $RC found."
	source $RC || error "Error in resource file $RC!"
	msg "And loaded."
    else
	msg ''
	msg "No resource file $RC found, or it is outdated. Creating one."
	cp $RC.default $RC || error "File copy fault!"
	msg "Resource file $RC created. Please edit it and restart SAR-make."
	exit 0
    fi
}    

getyesno ()
{
    if [ "$YES" = "-y" ] ; then
	echo 'SAR ==> Automatically proceeding.'
	$*
    else
	echo -n 'SAR ==> Press y to proceed, anything else to skip: '
	read ANS
	if [ "$ANS" = "y" ] ; then
	    $*
	else
	    msg 'Skipped.'
	fi
    fi
}

waitenter ()
{
    if [ "$TWOFLOP" = "yes" ] ; then
	msg 'Just press ENTER to proceed.'
	read
    fi
}    

msg ()
{
    echo -n 'SAR ==> ' 
    echo $*
}

error ()
{
    msg "Oops.. something went wrong!" $*
    echo -n "Trying to unmount floppy.. "
    umount $FLOPPY > /dev/null 2>&1
    echo "and to remove $TMP/sardisk directory."
    rm -r $TMP/sardisk > /dev/null 2>&1
    echo "Exiting."
    exit 1
}

syncdisk ()
{
    msg "Syncing."
    sync || error "Problem while syncing!"
    sync || error "Problem while syncing!"
    sync || error "Problem while syncing!"
}

insertdisk ()
{
    mount | grep $FLOPPY > /dev/null
    if [ $? -eq 0 ] ; then
	error "$FLOPPY is already mounted! Can't use that drive!"
    fi
    
    msg ''
    msg 'Insert a new but low-level formatted floppy into the drive.'
    msg 'This will be your' $*.
    waitenter
}

removedisk ()
{
    msg ''
    msg 'Remove the floppy from the drive.'
    msg 'Label it' $* 'and store it in a safe place.'
    waitenter
}

formatdisk ()
{
    msg ''
    msg 'About to format the ' $*.
    msg 'Insert it into the drive.. and'
    getyesno $MKFS $FLOPPY $DISKSIZE || error "Mkfs failure." \
	"Is the diskette low-level formatted?"
}

checkdisk ()
{
    msg ''
    msg 'About to check validity on the' $*.
    getyesno $FSCK $FLOPPY || error "Fsck failure. Crappy disk!"
}

mountdisk ()
{
    msg ''
    msg 'Mounting floppy' $* 'on' $TMP/sardisk '.'

    if [ ! -d $TMP/sardisk ] ; then
	mkdir -p $TMP/sardisk || error "Mkdir failure. Cannot create" \
	    $TMP/sardisk " directory!"
    fi

    mount -v $MOUNTFLAG $FLOPPY $TMP/sardisk || error "Mount failure." \
	"Cannot mount floppy on " $TMP/sardisk "!"

    msg 'Cleaning floppy of possible stale files.'
    rm -rf $TMP/sardisk/* || error "Rm failure. Cannot clean stale files!"
}

liloconfig ()
{
    echo boot = $FLOPPY				>  $TMP/sardisk/lilo.conf
    echo compact                                >> $TMP/sardisk/lilo.conf
    echo delay = 10                             >> $TMP/sardisk/lilo.conf
    echo message = /etc/message			>> $TMP/sardisk/lilo.conf
    echo install = /etc/boot.b			>> $TMP/sardisk/lilo.conf
    echo disktab = /etc/disktab			>> $TMP/sardisk/lilo.conf
    echo map = /lilo.map			>> $TMP/sardisk/lilo.conf
    echo verbose = 3                            >> $TMP/sardisk/lilo.conf
    echo backup = /dev/null                     >> $TMP/sardisk/lilo.conf
    echo image = /zImage			>> $TMP/sardisk/lilo.conf
    echo ramdisk = $DISKSIZE                    >> $TMP/sardisk/lilo.conf
    echo root = $FBOOT                          >> $TMP/sardisk/lilo.conf

    if [ $LILOAPPEND = "y" ] ; then
	echo "append = \"$APPEND\""		>> $TMP/sardisk/lilo.conf
    fi

    syncdisk

    lilo/lilo -r $TMP/sardisk -C lilo.conf || error \
	"Lilo error. Cannot make disk bootable!"
    
    rm $TMP/sardisk/lilo.conf
    cd ..
}

copyimage_aux ()
{
    $HOLECP $ZIMAGE $TMP/sardisk/zImage || \
	error "Cannot copy $ZIMAGE to floppy!"
    rdev $TMP/sardisk/zImage $FBOOT || error "Cannot change " \
	"floppy root device!"
    rdev -r $TMP/sardisk/zImage $DISKSIZE || error "Cannot change RAM" \
	"size on floppy!"
    rdev -R $TMP/sardisk/zImage 0 || error "Cannot change mount mode to r/w" \
	"on floppy zImage!"

    syncdisk
    liloconfig
    syncdisk
}    

copyimage ()
{
    msg ''
    msg 'About to copy kernel image file to floppy and to enable it thru LILO.'
    getyesno copyimage_aux
}

ddzimage ()
{
    msg ''
    msg 'About to dd the kernel image file to the boot floppy.'
    getyesno dd if=$ZIMAGE of=$FLOPPY
    rdev $FLOPPY $FBOOT || error "Cannot change floppy root device!"
    rdev -r $FLOPPY $DISKSIZE || error "Cannot change RAM size on floppy!"
    rdev -R $FLOPPY 0 || error "Cannot change mountmode to r/w on floppy!"
}    

makedev_aux ()
{
    cd $TMP/sardisk
    mkdir dev
    awk '{
	system (sprintf ("mknod -m %s %s %s %s %s", $6, $1, $2, $3, $4));
	system (sprintf ("chown %s %s", $5, $1));
    }' $TOPDIR/dev.lst	|| error "Fault in device creation!"
    cd $TOPDIR
    syncdisk
}

makedev ()
{
    msg ''
    msg 'About to make devices on floppy.'
    getyesno makedev_aux
}

whereis ()
{
    msg "Searching for $1.."
    WHEREIS_RES=""
    
    if [ -f "$1" ] ; then
	msg "Found it as-is."
	WHEREIS_RES="$1"
    else
	for SUBDIR in $SEARCH_DIRS ; do
	    if [ -f "$SUBDIR/$1" -a "$WHEREIS_RES" = "" ] ; then
		msg Found in $SUBDIR.
		WHEREIS_RES="$SUBDIR/$1"
	    fi
	done

	if [ "$WHEREIS_RES" = "" ] ; then
	    msg "Didn't resolve that name. Let's use find."
	    if [ "$ASSUME_ONE_DEV" = "yes" ] ; then
		FIND_RES=`find / -xdev -name $1 -print`
	    else
		FIND_RES=`find / -name $1 -print`
	    fi
	    if [ "$FIND_RES" != "" ] ; then
		WHEREIS_RES=`echo $FIND_RES | awk '{print $1}'`
		msg "Found it as $WHEREIS_RES."
	    else
		error "Failed to locate $1 on your disk!"
	    fi
	fi
    fi
}

configfiles ()
{
    msg "Your list of necessary files is not yet configured or needs to be"
    msg "reconfigured. Let's do that!"

    rm -f files.lst.configured > /dev/null 2>&1

    FLS=`cat files.lst`
    for F in $FLS
    do
	whereis $F
	if [ "$WHEREIS_RES" != "" ] ; then
	    echo $WHEREIS_RES >> files.lst.configured
	else
	    rm -f files.lst.configured
	    msg "I cannot find file $F ! Check the spelling of the file"
	    msg "and correct the error in \"files.lst\"."
	    error Aborting.
	fi
    done
}

copyfiles_aux ()
{
    if [ ! -f files.lst.configured -o files.lst -nt files.lst.configured ]
    then
	configfiles
    fi

    for f in `cat files.lst.configured` ; do
	# if it's a real file and no link, holecp it
	if [ -f $f -a ! -L $f -a ! -f $TMP/sardisk$f ] ; then
	    dir=`dirname $f`
	    if [ ! -d $TMP/sardisk$dir ] ; then
		mkdir -p $TMP/sardisk$dir || error \
		    "Failure to make directory $dir on SAR-disk!"
	    fi
	    $HOLECP -v $f $TMP/sardisk$f || error \
		"Error while attempting hole-copy!"
	# else just copy it, preserving stuff
	else
	    cp -adPv $f $TMP/sardisk || error \
		"Error while copying files to floppy!"
	fi
    done

    syncdisk
}

copyfiles ()
{
    msg ''
    msg 'About to copy necessary files to floppy.'
    getyesno copyfiles_aux
}

extrafiles_aux ()
{
    cd extra
    for f in `find .` ; do
	# if it's an ordinary file:
	if [ -f $f -a ! -L $f ] ; then
	    # kill any previous stuff on sardisk
	    if [ -f $TMP/sardisk/$f ] ; then
		msg "Warning: $f already on SAR disk, overruled from extra/"
		rm -f $TMP/sardisk/$f
	    fi
	    # holecopy it
	    $HOLECP -v $f $TMP/sardisk/$f || error \
		"Failure while hole-copying file $f from extra/!"
	# if it's a directory: create it on sardisk
	elif [ -d $f ] ; then
	    mkdir -p $TMP/sardisk/$f || error \
		"Failure to create dir $f on sardisk!"
	# fall-thru case: just use cp
	else
	    cp -adPv $f $TMP/sardisk  || \
		error "Failure while copying file $f from extra/!"
	fi
    done
    cd ..
    syncdisk
}

extrafiles ()
{
    msg ''
    msg 'About to copy extra files to floppy.'
    getyesno extrafiles_aux
}

unmountdisk ()
{
    msg ''
    msg 'Unmounting floppy' $* 'from' $TMP/sardisk '.'
    msg 'This may take some time, if the file buffers need to be flushed.'
    syncdisk
    umount $FLOPPY || error "Problem while unmounting floppy!"
    rm -r $TMP/sardisk
}

banner ()
{
    echo ''
    echo 'ICCE Search and Rescue Disk Maker  V' "$VER"
    echo 'Copyright (c) ICCE / Karel Kubat 1994. All rights reserved.'
    echo 'Another MegaHard production!'
    echo ''
    echo 'SAR-make by Karel Kubat, karel@icce.rug.nl'
    echo ''
}

usage ()
{
    echo 'Usage: SAR-make -y | -i'
    echo 'Where:'
    echo '    -y : will auto-answer most questions with "yes"'
    echo '    -i : will ask for answers (interactive)'
    echo 'Either -y or -i is required. Other definitions are read from'
    echo 'the file SAR-make.rc.'
    echo ''
    exit 1
}    

commandline ()
{
    if [ "$2" != "" -o "$1" = "" ] ; then
	usage
    elif [ "$1" = "-y" ] ; then
	YES=$1
    elif [ "$1" != "-i" ] ; then
	usage
    fi
}    
    

############################################################################
# Start of main program
############################################################################

VER="2.24"

############################################################################
# show banner, parse commandline flags, make sure we're root
banner
if [ `whoami` != root ] ; then
    echo '    You really should be root to make SAR disks.  Many programs'
    echo '    which are needed will fail when you attempt to run SAR-make'
    echo '    as a non-root user.'
    exit 1
fi    
commandline $*

############################################################################
# a few last initializations, plus resource file handling
TOPDIR=`dirname $0`
cd $TOPDIR
resourcefile $0
if [ "$TOPDIR" = "." ] ; then
    if [ "$PWD" = "" ] ; then
	error "PWD variable not found, cannot determine current directory!"
    fi
    TOPDIR=$PWD
fi    
HOLECP=$TOPDIR/miscstuff/holecp/holecp
PATH_DIRS=`echo $PATH | tr : ' '`
SEARCH_DIRS=`echo $PATH_DIRS $OTHER_DIRS`

############################################################################
# let's determine if we're making a two flop SAR system
if [ "$TWOFLOP" = "ask" ] ; then
    msg ''
    echo -n  'SAR ==> Do you wish to create a two-flop SAR system [yes/no] ? '
    read ans
    if [ "$ans" = "yes" ] ; then
	msg 'Ok, two floppy SAR system.'
	TWOFLOP="yes"
    elif [ "$ans" = "no" ] ; then
	msg 'Ok, all on one SAR flop.'
	TWOFLOP="no"
    else
	msg 'Hmmm.. I guess you mean "no" by that.'
	TWOFLOP="no"
    fi
    msg ''
fi

if [ "$TWOFLOP" = "yes" ] ; then
    FIRSTTARGET="BOOT DISK"
    SECONDTARGET="UTILITY DISK"
else
    FIRSTTARGET="BOOT AND UTILITY DISK"
    SECONDTARGET="BOOT AND UTILITY DISK"
fi

############################################################################
# Here goes now..
insertdisk $FIRSTTARGET
formatdisk $FIRSTTARGET
checkdisk  $FIRSTTARGET

if [ "$TWOFLOP" = "yes" ] ; then
    if [ "$LILOAPPEND" = "y" ] ; then
	msg "Warning: LILO append statements will not work"
	msg "on a two-floppy configuration! Only possible with"
	msg "a one-floppy system."
    fi
    ddzimage
    removedisk $FIRSTTARGET
    insertdisk $SECONDTARGET
    formatdisk $SECONDTARGET
    checkdisk  $SECONDTARGET
fi    

mountdisk  $SECONDTARGET
makedev 
copyfiles 
extrafiles
if [ "$TWOFLOP" = "no" ] ; then
    copyimage
fi    
unmountdisk $SECONDTARGET
removedisk  $SECONDTARGET

# All done.
exit 0
