#!/bin/bash

. bk_functions

yesno "Create root diskette?"

if [ "$?" != 0 ]
then
	exit
fi

yesno "$DISKETTEDEV will be destroyed! Continue?"

if [ "$?" != 0 ]
then
	exit
fi

msgbox "Insert diskette in $DISKETTEDEV"

infobox "Creating ext2 filesystem on $DISKETTEDEV"

mke2fs $DISKETTEDEV >/tmp/bootkit.log 2>&1
if [ $? -ne 0	]
then
	msgbox "mke2fs failed!"
	bkViewLog /tmp/bootkit.log
	exit
fi

#
infobox "Mounting floppy on $MOUNTPOINT"

mount -t ext2 $DISKETTEDEV $MOUNTPOINT >> /tmp/bootkit.log 2>&1

if [ $? -ne 0 ]
then
	msgbox "Unable to mount floppy!"
	bkViewLog /tmp/bootkit.log
  	exit
fi

# copy the directories containing files
for i in ./root_conf/files.*
do
	infobox "Copying files for $i directory"

	while read fname
	do	
		cp -dpP $fname $MOUNTPOINT >>/tmp/bootkit.log 2>&1
	done < $i
	#done < ./root_conf/files.$i
done

# Copy mini termcap file
infobox "Attempting to install mini-termcap file"

cat ./root_conf/termcap.* > /tmp/.termcap_cat 2>/dev/null

if [ -s /tmp/.termcap_cat ]
then
	cp -dp /tmp/.termcap_cat $MOUNTPOINT/etc/termcap
fi

# copy dev *without* trying to copy the files in it
infobox "Copying device files"

if [ ! -d "$MOUNTPOINT/dev" ]
then
	mkdir $MOUNTPOINT/dev >>/tmp/bootkit.log 2>&1
fi

while read fname
do
	cp -dpR $fname $MOUNTPOINT/dev >>/tmp/bootkit.log 2>&1
done < ./root_conf/devices

# create empty directories required
infobox "Creating additional directories"

if [ -f ./root_conf/dirs.extra ]
then
	while read dirname
	do
		if [ ! -d "$MOUNTPOINT$dirname" ]
		then
			mkdir $MOUNTPOINT$dirname >>/tmp/bootkit.log 2>&1
		fi
	done < ./root_conf/dirs.extra
fi

# Copy libc.so.? (COPYLIBC)

if [ "$COPYLIBC" = "ON" ]
then
	infobox "Copying runtime library (libc.so.?)"

	if [ ! -d "$MOUNTPOINT/lib" ]
	then
		mkdir $MOUNTPOINT/lib >>/tmp/bootkit.log 2>&1
	fi

	cp /lib/ld.so $MOUNTPOINT/lib >>/tmp/bootkit.log 2>&1
	cp -d $LIBCLINK $MOUNTPOINT/lib >>/tmp/bootkit.log 2>&1
	cp -p $LIBCLINK $MOUNTPOINT/lib >>/tmp/bootkit.log 2>&1

fi

# Copy any additional files or links found in the "root_skel" directory
infobox "Copying additional user-defined files"
cp -pR ./root_skel/* $MOUNTPOINT >> /tmp/bootkit.log 2>&1

# Append the "bootkit" superuser entry to the passwd file.  We do this just
# in case you forgot to put root's login shell (i.e /bin/ksh, etc) in the
# root_conf/files.bin file. ;-)

if [ "$ADDBKUSER" = "ON" ]
then
	infobox "Adding bootkit superuser passwd entry"
	
	if [ ! -d "$MOUNTPOINT/etc" ]
	then
		mkdir "$MOUNTPOINT/etc" >>/tmp/bootkit.log 2>&1
	fi

	echo "bootkit::0:0:Bootkit Superuser:/:/bin/sh" >>$MOUNTPOINT/etc/passwd

	chmod 644 "$MOUNTPOINT/etc/passwd" >>/tmp/bootkit.log 2>&1

	infobox "Syncing floppy disk"
	sync
	sleep 2
fi

umount $MOUNTPOINT

msgbox "Root diskette creation completed"

# Give the user a chance to view the log file
bkViewLog /tmp/bootkit.log

