#!/bin/sh
# $Id: loadwindowsCD.sh,v 1.5 2003/04/22 23:48:00 rwb Exp $ 
# SCCSID(@(#)loadwindowsCD.sh	1.82) Modified 20:22:01 10/18/01
# This script copies in Windows installation files a Windows 95/98 CD, then
# extracts the DOS files from it, and then "dosinstall"s those DOS files.
# ( NOTE: All the messages in this script must be NLSized! )
# Input:
#  Arg1 is the win95 or win98 directory or the CD directory that contains the
#	win95 or win98 directory.
#  Arg2 is not not specified or is the word "quiet".  This suppresses
#	all output to stdout and stderr.
# 	
# The output of this script is put in $VARMERGE/log/loadwindowsCD.log
# The output of the dosinstall is put in $VARMERGE/log/autodosi.log
#
# Exit values:
#		0 = Successful.
EX_SUCESSES=0
#		1 = Command line error.
EX_CMDLINE=1
#		2 = Already loaded.
EX_ALREADY_LOADED=2
#		3 = A working DOS is not already loaded.
EX_NO_DOS=3
#		4 = Specified CD directory does not seem to be correct.
EX_CD_DIR=4
#		5 = You do not have permission to install DOS.
EX_NO_PRIV=5
#		6 = User canceled the installation.
EX_USER_CANCEL=6
#		7 = DOS files are already copied from the CD-ROM.
# EX_ALREADY_COPIED=7	This is not used anymore.

# (Errors 10 and above only happen when the system is corrupted or Merge
# is not fully installed or working.)
#		10 = Unable to determine VARMERGE or STATICMERGE.
EX_VAR=10
#		11 = Required directories are missing.
EX_DIR_MISSING=11
#		12 = Required files are missing.
EX_FILE_MISSING=12
#		13 = Unable to create directories or files.
EX_CREATE_FAIL=13
#		14 = General CD-ROM error.
EX_CDROM_FAIL=14
#		15 = Other, hence bizzare unexpected error.
EX_BIZZARE=15

#SRI
#		16 = missing progress file required by SRI
EX_SRI_MISSING_PROGRESS_FILE=16
#		17 = missing floppy arguments
EX_SRI_MISSING_FLOPPY_ARGS=17
#		18 = No EULA agreement in place.
EX_NO_AGREEMENT=18
#ENDSRI

# Error values above 100 and below 100 are return codes from dosinstall
# that have been offset by 100.

# Set the umask to disable write permission for "group" and "other"
# for created files, and leave the other permissions intact.
umask 022

# Get the STATICMERGE, VARMERGE, and DOSWINBINDIR settings.
. /etc/mrgssv.sh

NULL=/dev/null
export NULL
ARG0=$0
VOL=loud
GUI=
COPYCOMPLETED=notdone
DO_RELOAD=no
SETUP_DIR=
WIN9x_DIR=
CDIR=
TMPDIR=
BATFILE=
KOPT="+kmerge-internal-config:snap"
DID_MOUNT=
MERGE_FORCEOKTORUN=y
export MERGE_FORCEOKTORUN
CAB_DIR="$VARMERGE/dosroot/wincabs"

#
# Disable HD0 emulation, since it gets in the way of loadwindowsCD
#
MERGE_DISABLE_HD0_EMULATION=on
export MERGE_DISABLE_HD0_EMULATION

if [ "$SYSTEMTYPE" = "linux" ]
then
	EOPT="-e"
else
	EOPT=
fi

ECHOE()
{
	echo $EOPT $*
}

Log()
{
	[ "z$LOGFILE" != "z" ] && ECHOE $* >> $LOGFILE
}

Echo()
{
	ECHOE $*
	[ "$VOL" = "loud" -a "z$LOGFILE" != "z" ] && ECHOE $* >> $LOGFILE
}

Exit()
{
	STATUS=$1
	cd /
	# Unmount the CD-ROM Drive if we mounted it ourselves.
	Unmount_NOW

	rm -f $VARMERGE/bootflop.dsk $VARMERGE/bootflopA.dsk
	if [ "x$CDIR" != "x" ]
	then
		rm -f "$CDIR/a[0-9]*.bat"
	fi

	# If there was any type of failure and the $VERNAME* files copied
	# from the Windows 95/98 CD are not completed then remove them.
	if [ $STATUS -ne 0 -a "$COPYCOMPLETED" != "completed" ]
	then
		$STATICMERGE/dos7utils -c >$NULL 2>&1
	fi
	# Remove the lock file doing_dosinst to indicate that we are
	# no longer in the middle of a dosinstall.
	$STATICMERGE/dos7utils -u >$NULL 2>&1

	[ "x$TMPDIR"  != "x" ] && rm -rf $TMPDIR
	[ "x$BATFILE" != "x" ] && rm -f  $BATFILE

	if [ "x$GUI" = "xgui" ]
	then
		if [ $STATUS -ne 0 ]
		then
			Echo
			Echo "DOS 7 installation failed."
			Echo "Press return to continue..."
			read XXX
		else
			sleep 5
		fi
	fi
	exit $STATUS
}

Unmount_NOW()
{
	# Unmount the CD-ROM Drive if we mounted it ourselves.
	case "_$DID_MOUNT" in
	_mount_cd)
		sleep 1
		$STATICMERGE/mcd -d $MERGE_CD_DEV_NAME -m $VARMERGE/mnt -u
		if [ $? -ne 0 ]
		then
			Echo "Warning: Can't unmount CD-ROM"
		else
			DID_MOUNT=
		fi
		;;
	_mount_dosc)
		$STATICMERGE/bin/mountc -u loadwin -d "$VARMERGE"/mnt
		if [ $? -ne 0 ]
		then
			Echo "Warning: Can't unmount partition"
		else
			DID_MOUNT=
		fi
		;;
	
	esac
}

interruptProc()
{
	trap 1 2 3 15
	Echo "Installation cancelled by the user."
	Exit $EX_USER_CANCEL
}
trap interruptProc 1 2 3 15

# Do a sync and sleep here to give enough time so that later checks
# for filesystem space are more likely to usefully accurate.
sync
sleep 5

if [ "$SYSTEMTYPE" = "linux" ]
then
	COMPRESS=gzip
	CEXT=gz
	CPIO_TYPE=" -H crc"
else
	COMPRESS=compress
	CEXT=Z
	CPIO_TYPE="c"
fi

#SRI

#    We are being called from the SRI (script runner interface) .  Do appropriate setup
SRI_startup()
{

	# set flag for future reference
	SRI_FROM_GUI=TRUE

	# open named pipe to report progress to easy installer via

	# first make sure the env var was set:
	[ -z "$SRI_PROGRESS_FILE" ] && Exit $EX_SRI_MISSING_PROGRESS_FILE
	SRI_FLOPPY_ARGS="sri_from_gui"
	if [ -n "$SRI_FLOPPY_DEV" ]
	then
		SRI_FLOPPY_ARGS="$SRI_FLOPPY_ARGS sri_floppy_dev $SRI_FLOPPY_DEV"
	fi
	if [ -n "$SRI_FLOPPY_FILE" ]
	then
		SRI_FLOPPY_ARGS="$SRI_FLOPPY_ARGS sri_floppy_file $SRI_FLOPPY_FILE"
	fi
	
	# now redirect the channel to that file
	#FIXME check for success?
	eval "exec ${SRI_PROGRESS_FD}> $SRI_PROGRESS_FILE"

	TRACE=trace
	# If we're not tracing, chuck the non-gui progress info
	#[ -z "$TRACE" ] && exec 1>/dev/null
}


SRI_output()
{
	[ -n "$SRI_FROM_GUI" ] && eval "echo $* >&$SRI_OUT_FD"
}

SRI_report_progress()
{
	[ "$1" = "$SRI_LAST_REPORTED_PROGRESS" ] && return
	[ -n "$SRI_FROM_GUI" ] && eval "echo $1 >&$SRI_PROGRESS_FD"
	SRI_LAST_REPORTED_PROGRESS=$1
}

SRI_FROM_GUI=""
SRI_OUT_FD=3
SRI_PROGRESS_FD=4

#END_SRI

while true
do
	[ "x$1" = "x" ] && break
	case $1 in
	trace)
		shift
		TRACE=trace
		;;
	quiet)
		# This is not an option we tell normal users about.
		shift
		VOL="quiet"
		;;
	silent)
		# This is not an option we tell normal users about.
		shift
		VOL="quiet"
		;;
	gui)
		# This is not an option we tell normal users about.
		shift
		GUI="gui"
		;;
	sri_from_gui)
		# This is not an option we tell normal users about.
		shift
		SRI_startup
		;;
	cddevice)
		if [ "x" != "x$WIN9x_DIR" ]
		then
			Echo "Error $EX_CMDLINE: Command line error."
			Exit $EX_CMDLINE
		fi
		shift
		if [ "x$1" = "x" ]
		then
			Echo "Error 22: cddevice value incomplete"
			Exit 22
		fi
		CDDEVICE=$1
		shift
		if [ ! -b $CDDEVICE ]
		then
			Echo "Error 33: Invalid CD-ROM device name specified:"
			Echo "        $CDDEVICE"
			Echo "Cannot continue.\n"
			Exit 33
		fi
		;;
	dosc)
		shift
		USE_DOSC=use_dosc
		;;
	fromdir)
		if [ "x" != "x$CDDEVICE" ]
		then
			Echo "Error $EX_CMDLINE: Command line error."
			Exit $EX_CMDLINE
		fi
		shift
		if [ "x$1" = "x" ]
		then
			Echo "Error 18: fromdir value incomplete"
			Exit 18
		fi
		WIN9x_DIR=$1
		shift
		;;
	subdir)
		shift
		SETUP_DIR=$1
		shift
		;;
	reload)
		shift
		DO_RELOAD=yes
		;;
	wincabs)
		# Specifies where to place the cab files.
		shift
		if [ "x$1" = "x" ]
		then
			Echo "Error 18: fromdir value incomplete"
			Exit 18
		fi
		CAB_DIR="$1"
		shift
		;;
	*)
		[ "$VOL" = "quiet" -o "x$GUI" = "xgui" ] && Exit 14
		Log "Error 14: Unknown parameter $1"
		ECHOE ""
		Log   "Error 14: Unknown parameter $1"
		echo
		echo "Usage: loadwindowsCD [cddevice xxx | fromdir xxx | dosc ] [subdir xxx] [reload]"
		echo
		echo "The options are:"
		echo "cddevice xxx   - Specify the UNIX device name xxx of"
		echo "                 the CD drive."
		echo "fromdir xxx    - Specify the UNIX directory xxx where the"
		echo "                 CD is mounted on the UNIX filesystem or"
		echo "                 where a copy of the contents of the CD"
		echo "                 was copied."
		echo "dosc           - Load from the native DOS C drive."
		echo "subdir  xxx    - Specify the sub-directory where the"
		echo "                 EXTRACT program and the CAB files are".
		echo "reload         - Reload the Windows files.  This is used"
		echo "                 when the Windows files have previously"
		echo "                 been loaded and you want to wipe that"
		echo "                 out and reload all the files."
		echo
		echo "Note: Options cddevice, fromdir and dosc cannot be used"
		echo "at the same time."
		echo
		ECHOE ""
		# Other valid options that are for internal Merge use only:
		#     gui, silent, quiet, trace
		Exit 14
		;;
	esac
done

if [ "z$LOGFILE" = "z" ]
then
	LOGFILE=$VARMERGE/log/loadwindowsCD.log
	rm -f $LOGFILE 2> /dev/null
	touch $LOGFILE 2> /dev/null
	if [ ! -f $LOGFILE -o -s $LOGFILE ]
	then
		LOGFILE=$HOME/loadwindowsCD.log
		rm -f $LOGFILE 2> /dev/null
		touch $LOGFILE 2> /dev/null
	fi
	if [ ! -f $LOGFILE -o -s $LOGFILE ]
	then
		LOGFILE=/dev/null
	fi
	date > $LOGFILE
fi
TOOLDIR=$STATICMERGE
DOSI_DIR=$VARMERGE/dosi
if [ ! -d $DOSI_DIR ]
then
	Echo $ARG0:
	Echo "Error: Required directroy $DOSI_DIR is missing!!!"
	Echo "Cannot continue.\n"
	Exit $EX_DIR_MISSING
fi

if [ ! -x $STATICMERGE/dos7utils ]
then
	Echo $ARG0:
	Echo "Error: Required file $STATICMERGE/dos7utils is missing!!!"
	Echo "Cannot continue.\n"
	Exit $EX_DIR_MISSING
fi

# The above set up the intrastructure and parsed the command line
# options, so now we are ready to do the actual work!

# # # # # # # # # # # # # # #   # # # # # # # # # # # # # # #
# # # # # Functions # # # # #   # # # # # Functions # # # # #
# # # # # # # # # # # # # # #   # # # # # # # # # # # # # # #

# Only return if have permission to write in various directories
# that normally only are writeable if logged in as root.
# The parameter indicates which message to print out if not root.
Check_Root()
{
	if [ -w $VARMERGE -a -w $VARMERGE/dosi -a -w $VARMERGE/dosroot/dos \
		-a -w $VARMERGE/dosroot ]
	then
		return
	fi
	# Print out an appropriate message and then exit.
	Log "Check_Root $1: not root"
	if [ "$VOL" != "loud" ]
	then
		Exit $EX_NO_PRIV
	fi
		
	case $1 in
	root_only)
		ECHOE ""
		echo "You do not have permission to load Windows."
		echo "You must be logged in as root to do this."
		ECHOE ""
		;;
	fixup_needed)
		ECHOE ""
		echo "The currently loaded Windows/DOS is not installed"
		echo "properly, or is corrupted."
		echo "So that this can be fixed, you must log in as"
		echo "'root' and retry."
		ECHOE ""
		;;
	*)
		# This should never happen, but just in case have a message
		# ready.
		echo "You must be logged in as root to do this."
		;;
	esac
	Exit $EX_NO_PRIV
}

Check_EULA()
{
	AGREE=no
	if [ -f "$VARMERGE/agree.txt" ]
	then
		grep "^The user agreed to the End User License Agreement\$" \
			"$VARMERGE/agree.txt" > /dev/null 2>&1
		if [ $? -eq 0 ]
		then
			AGREE=yes
		fi
	fi
}

EULA_Query()
{
	# On non-Linux systems make sure the user has agreed the to
	# the EULA and that a proper license file is installed.
	[ "$SYSTEMTYPE" != "linux" ] && return
	Check_EULA
	if [ "$AGREE" != "yes" ]
	then
		#SRI
		# We are running from easy install, so don't query the user.
		[ -n "$SRI_FROM_GUI" ] && exit $EX_NO_AGREEMENT
		#ENDSRI
		"$STATICMERGE"/bin/ask_eula.sh
		Check_EULA
		if [ "$AGREE" != "yes" ]
		then
			Echo ""
			Echo "End User License has not been agreed to."
			Echo "Cannot continue."
			exit $EX_NO_AGREEMENT
		fi
	fi
}

License_Query()
{
	[ "$SYSTEMTYPE" != "linux" ] && return
	[ -n "$SRI_FROM_GUI" ] && return
	# Make sure that we are licensed.
	"$STATICMERGE"/bin/ask_license.sh 2> /dev/null
}


# Function Get_CD_DEVICE()
#	Set the global MERGE_CD_DEV_NAME with the CD device name we 
#	are to use. Note: This is only called from Setup_CD_ROM()
#	which is called only when NOT installing from a directory.
Get_CD_DEVICE()
{
	echo $* >> $LOGFILE
	Log Get_CD_DEVICE
	if [ "x$CDDEVICE" != "x" ]
	then
		MERGE_CD_DEV_NAME="$CDDEVICE"
		return
	fi

	if [ ! -s $DEFAULTMERGE ]
	then
		Echo "Error 15: Missing file $DEFAULTMERGE"
		Echo "Cannot continue.\n"
		Exit 15
	fi
	MERGE_CD_DEV_NAME=
	eval `grep "^MERGE_CD_DEV_NAME=" $DEFAULTMERGE`
	if [ "x$MERGE_CD_DEV_NAME" = "x" ]
	then
		Echo "Error 16: No CD device name specified and no default"
		Echo "MERGE_CD_DEV_NAME setting in file $DEFAULTMERGE."
		Echo "Cannot continue.\n"
		Exit 16
	fi
	if [ ! -b $MERGE_CD_DEV_NAME ]
	then
		Echo "Error 17: Invalid CD-ROM device name specified in $DEFAULTMERGE"
		Echo "(MERGE_CD_DEV_NAME=$MERGE_CD_DEV_NAME)"
		Echo "Cannot continue.\n"
		Exit 17
	fi
	Log Using cd drive setting from /etc/default/merge: $MERGE_CD_DEV_NAME
	return
}

# Find out which DOS version, if any, is currently installed.
# Sets CURRENT_DOS to one of DOS70, DOS71, OLDDOS, NODOS, or UNKNOWN.
Check_installed_DOS_type()
{
	Log Check_installed_DOS_type
	if [ ! -s $VARMERGE/dosroot/dos/version.dos ]
	then
		# This is no DOS currently installed.
		CURRENT_DOS=NODOS
		Log "No DOS is installed."
		return
	fi
	WVAL=`grep -i "^WDOS_VER=" $VARMERGE/dosroot/dos/version.dos`
	case "$WVAL" in
	*DOS80*)
		# This is dos 8.0
		CURRENT_DOS=DOS80
		Log "DOS 8.0 is installed"
		return
		;;
	*DOS71*)
		# This is dos 7.1
		CURRENT_DOS=DOS71
		Log "DOS 7.1 is installed"
		return
		;;
	*DOS70*)
		# This is dos 7.0
		CURRENT_DOS=DOS70
		Log "DOS 7.0 is installed"
		return
		;;
	*OLDDOS*)
		# This is old dos (6.x or even older)
		CURRENT_DOS=OLDDOS
		Log "PRE-DOS 7.0 is installed"
		return
		;;
	*)
		CURRENT_DOS=UNKNOWN
		Log "$VARMERGE/dosroot/dos/version.dos is damaged."
		return
		;;
	esac
}

Mount_CD()
{
	$STATICMERGE/mcd -d $MERGE_CD_DEV_NAME -m $VARMERGE/mnt -u
	$STATICMERGE/mcd -d $MERGE_CD_DEV_NAME -m $VARMERGE/mnt -c
	if [ $? -eq 0 ]
	then
		DID_MOUNT=mount_cd
		WIN9x_DIR=$VARMERGE/mnt
		return
	fi
	if [ $1 -eq 0 ]
	then
		Echo "Error 50: Can't setup CD ROM."
		Exit 50
	fi
	# Try again.  Sometimes the first accesses fails,
	# and waiting for spin-up is all that is needed.
	sleep 3
	Mount_CD `expr $1 - 1`
}

Setup_CD_ROM()
{
	Get_CD_DEVICE
	Mount_CD 3
}

Mount_dosc()
{
	
	rmdir "$VARMERGE"/mnt/loadwin	2> /dev/null
	mkdir "$VARMERGE"/mnt		2> /dev/null
	mkdir "$VARMERGE"/mnt/loadwin	2> /dev/null
	if [ ! -d "$VARMERGE"/mnt/loadwin ]
	then
	   Echo "Error 50: Can't create mount point for the native DOS C drive."
	   Exit 50
	fi
	$STATICMERGE/bin/mountc -u loadwin -d "$VARMERGE"/mnt 2> /dev/null
	$STATICMERGE/bin/mountc -m loadwin -d "$VARMERGE"/mnt -t short
	if [ $? -ne 0 ]
	then
		Echo "Error 50: Can't mount the native DOS C drive."
		Exit 50
	fi
	DID_MOUNT=mount_dosc
	WIN9x_DIR=$VARMERGE/mnt/loadwin
	[ "x$SETUP_DIR" != "x" ] && return

	cd "$WIN9x_DIR"
	SETUP_DIR=`find . -type f | grep -i win95_03.cab \
		| sed -e 's/^\.\///' \
		| sed -e 's/\/[wW][iI][nN]95_03.[cC][aA][bB]//'`
	if [ "x$SETUP_DIR" = "x" ]
	then
		SETUP_DIR=`find . -type f | grep -i win98_22.cab \
			| sed -e 's/^\.\///' \
			| sed -e 's/\/[wW][iI][nN]98_22.[cC][aA][bB]//'`
	fi
	if [ "x$SETUP_DIR" = "x" ]
	then
		SETUP_DIR=`find . -type f | grep -i win_8.cab \
			| sed -e 's/^\.\///' \
			| sed -e 's/\/[wW][iI][nN]_8.[cC][aA][bB]//'`
	fi
	if [ "x$SETUP_DIR" = "x" ]
	then
		Echo "Error, Unable to locate the Windows setup directory."
		Exit 50
	fi 
}


# Function: Run_Dosinstall_Now
# Input variables:
#	VERNAME
#	STATICMERGE
#	VARMERGE
#	DOSI_DIR
# Returns values:
# When dosinstall returned 0, then return 0.
# When dosinstall returns >0, then return that number plus 100.
# When dosinstall returns <0, then return that number minus 100.
Run_Dosinstall_Now()
{
	cd $DOSI_DIR

	Log "Running dosremove"
	$STATICMERGE/dos7utils -r 			>> $LOGFILE 2>&1
	Log "Running dosinstall"
	$STATICMERGE/dos7utils -i		>> $LOGFILE 2>&1
	RETVAL=$?

	# dosinstall (called via dos7utils -i) removed the lock file.
	#
	# At this point DOS is completely installed so we don't care if
	# someone starts up a Merge session.  Thus, we don't need to create
	# the lock file doing_dosinst.

	Log "The return code from dosinstall is $RETVAL"
	if [ $RETVAL -eq 0 ]
	then
		# Everything is installed correctly, so finalize the
		# ownership and mode of the *$VERNAME* files.
		$STATICMERGE/dos7utils -b
		return $EX_SUCESSES
	fi
	[ $RETVAL -gt 0 ] && return `expr $RETVAL + 100`
	return `expr $RETVAL - 100`
}

# # # # # # # # # # # # # # #   # # # # # # # # # # # # # # #
 # # # # # Main  # # # # # # # # # # # # #  Main # # # # # #
# # # # # # # # # # # # # # #   # # # # # # # # # # # # # # #

Log "Log of $ARG0"
Log "`date`"
Echo "Checking the system."

# We would like to allow the first time load of Windows to be
# about to be done by a normal user, but now, only root is allowed.
Check_Root root_only
EULA_Query

# Create the lock file doing_dosinst to indicate that we are in the
# middle of a dos install.
$STATICMERGE/dos7utils -l				>> $LOGFILE 2>&1

Check_installed_DOS_type
# At this point CURRENT_DOS is one of DOS71, DOS70, OLDDOS, NODOS, or UNKNOWN.
if [ "$CURRENT_DOS" = "UNKNOWN" ]
then
	# Something is screwy.  We only want to continue if we
	# are logged in as root so we can fix things up.
	# If not root, Check_Root will not return.
	Check_Root fixup_needed
elif [ "$CURRENT_DOS" != "NODOS" ]
then
	# When DOS is currently installed, then normal
	# users are not allowed to re-install DOS.
	# If not root, Check_Root will not return.
	Check_Root root_only
fi

VERNAME=ms7cd

cd $DOSI_DIR
FFILE=`echo $CAB_DIR/* | cut -f1 -d' '`
if [ -f "$FFILE" ]
then
	IS_LOADED=yes
	if [ "$DO_RELOAD" = "no" ]
	then
		Log "Windows is already loaded!."
		ECHOE ""
		echo "Windows is already loaded or partially loaded."
		echo ""
		if [ "x$GUI" = "xgui" ]
		then
			echo "If you want to completely remove the currently"
			echo "loaded Windows files and reload fresh from the"
			echo "Windows installation CD, then you must run the"
			echo "'unloadwindowsCD' command first."
			echo ""
			echo "(You must be logged in as root to do this.)"
		else
			echo "If you want to completely remove the currently"
			echo "loaded Windows files and reload fresh from the"
			echo "Windows installation CD, then use the 'reload'"
			echo "option."
			echo ""
			echo "You must be logged in as root to do this.)"
		fi
		ECHOE ""
		License_Query
		Log "Returning value $EX_ALREADY_LOADED"
		Exit $EX_ALREADY_LOADED
	fi
elif [ \( -s ${VERNAME}.set -a -s ${VERNAME}.vdl   \) -a \
       \( -s ${VERNAME}.dsk  -o -s ${VERNAME}.dsk.${CEXT} \) -a \
       \( -s ${VERNAME}.cpio -o -s ${VERNAME}.cpio.${CEXT} \) ]
then
	IS_LOADED=yes
	if [ "$DO_RELOAD" = "no" ]
	then
		Log "DOS is already loaded!."
		ECHOE ""
		echo "DOS files are currently loaded."
		echo ""
		echo "Loading the Windows files will also replace the"
		echo "loaded DOS files."
		if [ "x$GUI" = "xgui" ]
		then
			echo "To load the Windows files (and replace the DOS"
			echo "files), then you must run the 'unloadwindowsCD'"
			echo "command first."
			echo "You must be logged in as root to do this.)"
		else
			echo "To load the Windows files (and replace the DOS"
			echo "files), then use the 'reload' option."
			echo ""
			echo "You must be logged in as root to do this.)"
		fi
		ECHOE ""
		License_Query
		Log "Returning value $EX_ALREADY_LOADED"
		Exit $EX_ALREADY_LOADED
	fi
fi
if [ "$IS_LOADED" = "yes" ]
then
	# Only root can do a "reload".
	# If not root, Check_Root will not return.
	Check_Root root_only
	Log "Removing Windows/DOS files previously copied in."
	rm -f *${VERNAME}.set
	rm -f *${VERNAME}.vdl
	rm -f *${VERNAME}.dsk*
	rm -f *${VERNAME}.cpio*
	[ ! -s default.set ] && rm -f default.set
	Log "Removing wincabs files."
	rm -rf $CAB_DIR/*
	rm -f $VARMERGE/bootflop.dsk $VARMERGE/bootflopA.dsk
fi

if [ "$CURRENT_DOS" != "NODOS" ]
then
	# Remove the existing installed DOS if any.
	#
	# Previously "Check_Root" was called to verify that
	# the current user is root, so it is OK to try to remove DOS now.
	#
	# It is prefered to do this when installing DOS from a windows CD,
	# because we don't really know if the currently installed DOS is
	# suitable for installing the DOS from the CD.
	# We know that DOS 7.1 on the OSR2 disks cannot be used to install
	# the DOS 7.0, because the 7.1 "sys" command refuses to be run from
	# DOS 7.0.  (Perhaps using "setver" would solve the problem.)
	# Also we know that in some situations running extract using DOS 6.x
	# results in "Out of memory" errors.  But there are not problems
	# using DOS 6.x to run extract in other situations.  (One that works
	# is the extracts run from the batch file that creates the bootable
	# floppy!  If we could spend some more time on this we could
	# probably work things so that we could avoid removing the
	# currently installed DOS here in most situations and thus not need
	# to do the "preinstall" in upgrade scenarios thus saving a bit of
	# time.  But the overall point is to replace the currently installed
	# DOS, and the time saving is probably not worth the effort.
	
	Log "Running dosremove"
	$STATICMERGE/dosremove			>> $LOGFILE 2>&1
fi

# The first parameter is the directory of either where the CD is mounted
# or the win95 or win98 directory.  If WIN9x_DIR is set, then that is used
# instead of the parameter.

if [ "x$USE_DOSC" = "xuse_dosc" ]
then
	Echo "Checking the native DOS C drive."
	Mount_dosc
	cd $DOSI_DIR
elif [ "x$WIN9x_DIR" = "x" ]
then
	Setup_CD_ROM
fi
if [ -n "$SETUP_DIR" ]
then
	WIN9x_DIR="${WIN9x_DIR}"/"$SETUP_DIR"
fi
if [ -d "$WIN9x_DIR"/win95 ]
then
    if [ -f "$WIN9x_DIR"/win95/extract.exe -o -f "$WIN9x_DIR"/win95/EXTRACT.EXE ]
    then
    	# This is Windows 95.
	WIN9x_DIR="$WIN9x_DIR"/win95
    fi
else
    if [ -f "$WIN9x_DIR"/win98/extract.exe -o -f "$WIN9x_DIR"/win98/EXTRACT.EXE ]
    then
    	# This is Windows 98 -- Original or "Second Edition" (SE)
	WIN9x_DIR="$WIN9x_DIR"/win98
    elif [ -f "$WIN9x_DIR"/win9x/extract.exe -o -f "$WIN9x_DIR"/win9x/EXTRACT.EXE ]
    then
	# This is Windows "Millennium Edition (ME) 
	WIN9x_DIR="$WIN9x_DIR"/win9x
    fi
fi
NotFound()
{
	Log "Did not find file $i"
	ECHOE ""
	Echo 
	case "_$DID_MOUNT" in
	_mount_cd)
		Echo "Did not find the Windows installation files."
		Echo "Either the CD is not a full Windows installation CD"
		Echo "or the needed files are in a subdirectory on the CD."
		if [ "x$GUI" = "x" ]
		then
			Echo "Or the Windows CD is not mounted properly."
			Echo
		fi
		;;
	_mount_dosc)
		Echo "The native DOS drive C does not have the required"
		Echo "Windows installation files."
		;;
	*)
		Echo "The specified directory not have the required"
		Echo "Windows installation files."
		;;
	esac
	if [ "x$SETUP_DIR" = "x" ]
	then
		Echo "No subdirectory to use was specified."
		Echo "Perhaps a subdirectory needs to be specified."
	else
		Echo "The following sub directory to use was specified:"
		Echo "   $SETUP_DIR"
		Echo
		Echo "Perhaps this is not the correct location."
	fi
	Echo
	Echo "To install using the 'loadwindowsCD' command, the 'subdir'"
	Echo "option is used to specify the subdirectory to load from."
	Echo "The directory that needs to be specified is where the EXTRACT"
	Echo "program and the CAB files are located, and where the SETUP"
	Echo "command exists. (The 'setup' command might be one of the"
	Echo "following, depending on the language version of Windows:"
	Echo "    setup.exe install.exe config.exe instalar.exe asenna.exe"
	Echo "    instala.exe setupcur.exe instal.exe kur.exe"
	ECHOE ""
	Log "Returning value $EX_CD_DIR"
	Exit $EX_CD_DIR
}

[ "x$WIN9x_DIR" = "x" ] && NotFound extract.exe
cd $WIN9x_DIR
# Make sure the extract.exe and the precopy1.cab file is there.
for i in extract.exe precopy1.cab
do
	CHECK_FILE="`ls | grep -i $i`"
	[ -z "$CHECK_FILE" ] && NotFound $i
done
# And make sure the "setup" command is there too.  (The different
# language versions have a different filename for this command.)
FOUND_SETUP=not_found
for i in setup.exe install.exe config.exe instalar.exe asenna.exe instala.exe \
         setupcur.exe instal.exe kur.exe
do
	CHECK_FILE="`ls | grep -i $i`"
	[ -z "$CHECK_FILE" ] && continue 
	FOUND_SETUP=found_setup
	break
done
if [ "$FOUND_SETUP" != "found_setup" ]
then
	NotFound setup
fi

# If we get this far then we have a valid directory because
# it has both the extract.exe program and one of the required cab files.
# So we don't expect to fail to find the rest of the required cab files.

# Determine the names of the CAB files and which version of Windows.

# Some fun facts about various English Windows 9x versions:
#   Win95-classic - Upgrade:
#		first win cab file: win95_02.cab
#		last  win cab file: win95_17.cab
#		last file:  xmsmmgr.exe
#   Win95-classic - Full:
#		first win cab file: win95_03.cab
#		last  win cab file: win95_21.cab
#		last file: xmsmmgr.exe
#   Win95-OSR2:
#		first win cab file: win95_02.cab
#		last  win cab file: win95_28.cab
# 		last file: xmsmmgr.exe
#   Win98-original:
#		first win cab file: win98_22.cab
#		last  win cab file: win98_69.cab
# 		last file: xmsmmgr.exe
#   Win98-second-edition:
#		first win cab file: win98_21.cab
#		last two cab files: win98_74.cab and win98_ol.cab
# 		last file: xmsmmgr.exe
#   WinME:
#		first win cab file: WIN_8.CAB
#		last two cab files: WIN_22.CAB and WIN_OL.CAB
# 		last file: xmsmmgr.exe
# ---
Get_First_Win_Cab()
{
	FOUND_WIN95=no
	FOUND_WIN98=no
	FOUND_WINME=no
	WIN_CAB=failed
	# Is it Win95?
	for i in win95_*.cab
	do
		if [ -f $i ]
		then
			WIN_CAB=$i
			FOUND_WIN95=yes
			return
		fi
	done
	for i in WIN95_*.CAB
	do
		if [ -f $i ]
		then
			WIN_CAB=$i
			FOUND_WIN95=yes
			return
		fi
	done
	# It is not a Win95, so see if it is Win98.
	for i in win98_*.cab
	do
		if [ -f $i ]
		then
			WIN_CAB=$i
			FOUND_WIN98=yes
			return
		fi
		break;
	done
	for i in WIN98_*.CAB
	do
		if [ -f $i ]
		then
			WIN_CAB=$i
			FOUND_WIN98=yes
			return
		fi
	done
	# It is not Win95 or Win98, so see if it is WinME.
	for i in win_*.cab
	do
		if [ -f $i ]
		then
			WIN_CAB=$i
			FOUND_WINME=yes
			return
		fi
	done
	for i in WIN_*.CAB
	do
		if [ -f $i ]
		then
			WIN_CAB=$i
			FOUND_WINME=yes
			return
		fi
	done
}
Get_First_Win_Cab

if [ "$WIN_CAB" = "failed" ]
then
	ECHOE ""
	Echo "Did not find any the CAB files".
	Echo 
	Echo "Perhaps the CD is damaged or it is a new release that"
	Echo "currently we cannot load Windows from."
	ECHOE ""
	Log "Returning value $EX_CD_DIR"
	Exit $EX_CD_DIR
fi
ECHOE ""

# Determine which version of Windows, and how much space is
# needed.  The extra 10MB pad is to take care of
# $VARMERGE/dosi, $VARMERGE/dosroot/dos and $VARMERGE/image
# when the wincabs directory is in the same filesystem as they are.
# (Actually only 6MB extra is needed, but for some slop and
# the idea that you should not run the filesystem completely
# out of room, the pad is larger.)
# NOTICE: the WINDOWS_VERSION variable in installwindows.sh and 
#	  the Win95VersionInfo[].w9x_VerName should use the same
#	  value as here!!!
if [ "$FOUND_WIN98" = "yes" ]
then
	# It is Windows 98, so find out which version.
	if [ -f win98_73.cab -o -f WIN98_73.CAB ]
	then
                if [ -f win98_86.cab -o -f WIN98_86.CAB ]
                then
		     WINDOWS_VERSION=98sejp
		     # Need at least 147 MB for the cabs, but pad it up to 157.
		     WINMB=157
                elif [ -f win98_80.cab -o -f WIN98_80.CAB ]
		then
                     WINDOWS_VERSION=98sezhcn
		     # Need at least 135 MB for the cabs, but pad it up to 145.
		     WINMB=145
                elif [ -f win98_76.cab -o -f WIN98_76.CAB ]
		then
                     WINDOWS_VERSION=98sezhtw
		     # Need at least 125 MB for the cabs, but pad it up to 135.
		     WINMB=135
	        elif [ -f win98_74.cab -o -f WIN98_74.CAB ]
		then
                     WINDOWS_VERSION=98se
		     # Need at least 132 MB for the cabs, but pad it up to 142.
		     WINMB=142
		else
                     WINDOWS_VERSION=98sekr
		     # Need at least 125 MB for the cabs, but pad it up to 135.
		     WINMB=135
                fi
	else
		# English win98orig, win98_22-69.cab
		WINDOWS_VERSION=98orig
		# Need at least 115 MB for the cabs, but pad it up to 125.
		WINMB=125
	fi
elif [ "$FOUND_WIN95" = "yes" ]
then
	# It is Windows 95, so find out which version.

	# Note! It is never safe to use the number of cab files to
	# find if this is osr2! Some locales have 28 cabs files but
	# some others only have 26! The only safe way is to use the
	# old check for msinfo.inf and the string OSR2 in the file!
	if [ -f msinfo.inf ]
	then
		grep -q OSR2 msinfo.inf
		if [ $? -eq 0 ]
		then
			WINDOWS_VERSION=95osr2
			# Need at least 69 MB for the cabs, but pad it up to 79.
			WINMB=79
		else
			WINDOWS_VERSION=95classic
			# Need at least 40 MB for the cabs, but pad it up to 50.
			WINMB=50
		fi
	else
		WINDOWS_VERSION=95classic
		# Need at least 40 MB for the cabs, but pad it up to 50.
		WINMB=50
	fi
elif [ "$FOUND_WINME" = "yes" ]
then
	WINDOWS_VERSION=9xme
	# Need at least 160 MB for the cabs, but pad it up to 170.
	WINMB=170
else
	# This cannot happen, but if someone screws up the script,
	# we need to protect ourselves by bailing early so
	# that the problem can be found quickly.
	Echo "Internal error #1 in installwindowsCD"
	exit $EX_BIZZARE
fi
Log "Found Windows $WINDOWS_VERSION"

# We have seen cases on Linux where the CD seems properly mounted
# but the last several files at the end of the win95 directory
# are not seen.  Often retrying the mount makes them visible.
# So we check for this problem by checking for the last file
# we expect to see in the win95/98 installation directory.
# So, it is sufficient to just check for the file xmsmmgr.exe because
# this is the last file in the directory for all known versions.
if [ ! -f xmsmmgr.exe -a ! -f XMSMMGR.EXE ]
then
	ECHOE ""
	Echo "Did not find all the expected files in the Windows"
	Echo "installation directory $WIN9x_DIR"
	Echo "Expected to find file xmsmmgr.exe"
	Echo 
	Echo "Perhaps the CD is damaged.  Sometimes marginal CDs"
	Echo "or CD drives will work if you retry the installation."
	Echo "Contents of ${WIN9x_DIR}:"
	ls -C $WIN95xDIR
	ECHOE ""
	Log "Returning value $EX_FILE_MISSING"
	Exit $EX_FILE_MISSING
fi

# The directory $VARMERGE/instC should already exist, but make sure.
# This directory is where the "merge-internal-config:snap" configuration
# has it's C drive located.
CDIR=$VARMERGE/instC
if [ ! -d $CDIR ]
then
	mkdir $CDIR		>> $LOGFILE 2>&1
	if [ ! -d $CDIR ]
	then
		Echo "Missing directory: $CDIR"
		Echo "Exiting..."
		Log "Returning value $EX_CREATE_FAIL"
		Exit $EX_CREATE_FAIL
	fi
	chmod 775 $CDIR		>> $LOGFILE 2>&1
	chgrp bin $CDIR		>> $LOGFILE 2>&1
	chown bin $CDIR		>> $LOGFILE 2>&1
fi

##########################################################################
##########################################################################
###  Should add checks here for adequate disk space here, now that
###  we know which version of DOS.
###  (Use similar code as in dosinstall.)
##########################################################################
##########################################################################

##########################################################################
# NOTE: All further code must have matching cleanup code in "Exit()".
#  E.g. $TMPDIR must be removed.
##########################################################################


cd $DOSI_DIR
if [ ! -f $VARMERGE/dosroot/dos/version.dos ]
then
	# Create empty files with the user as the owner in a restricted
	# (own by root) directory so that the user can write to these files.
	$STATICMERGE/dos7utils -t			>> $LOGFILE 2>&1
fi

# Copy the win95 files into a standard place.
if [ ! -d "$CAB_DIR" -a ! -L "$CAB_DIR" ]
then
	mkdir     "$CAB_DIR"
	chown bin "$CAB_DIR"
	chgrp bin "$CAB_DIR"
	chmod 775 "$CAB_DIR"
fi
rm -rf $CAB_DIR/* 2>/dev/null

# Do a sync and sleep to hopefully give enough time
# for the statfs that dfmerge does to return accurate numbers.
sync
sleep 1
# Check the free space in the filesystem where the cab files are to be put.
FREE_KB=`$STATICMERGE/dfmerge -k "$CAB_DIR"`
FREEMB=`expr $FREE_KB / 1024`
if [ $FREEMB -lt $WINMB ]
then
	Echo ""
	Echo "Cannot load the Windows files because there is not enough"
	Echo "disk space in the filesystem to load the Windows files"
	Echo "into $CAB_DIR"
	Echo "You need to have at least $WINMB MB available and"
	Echo "currently there is only $FREEMB MB available."
	Log "Returning value $EX_CREATE_FAIL"
	Exit $EX_CREATE_FAIL
fi

# For the cases where $CAB_DIR is not in the same filesystem as $VARMERGE,
# check for enough space for the DOS stuff that is put in $VARMERGE.
FREE_KB=`$STATICMERGE/dfmerge -k "$VARMERGE"`
FREEMB=`expr $FREE_KB / 1024`
REQUIRED_MB=10
if [ $FREEMB -lt $REQUIRED_MB ]
then
	Echo ""
	Echo "Cannot load the Windows files because there is not enough"
	Echo "disk space for required files in $VARMERGE"
	Echo "You need to have at least $REQUIRED_MB MB available and"
	Echo "currently there is only $FREEMB MB available."
	Log "Returning value $EX_CREATE_FAIL"
	Exit $EX_CREATE_FAIL
fi


ClearFloppyImage()
{
	B_F="$1"
	TMPFILE2="$VARMERGE"/tmp/user_flop_t2
	echo dir | "$STATICMERGE"/dosdisk -s "$B_F" > "$TMPFILE2"
	grep -i command.com "$TMPFILE2" > /dev/null
	if [ $? -ne 0 ]
	then
		# Failed!
		rm  "$TMPFILE2"
		return 1
	fi
	for i in `cat "$TMPFILE2"`
	do
		case $i in
		command.com|io.sys|winboot.sys|format.com|sys.com)
			continue
			;;
		esac
		echo delete $i | "$STATICMERGE"/dosdisk -s "$B_F"
	done
	rm  "$TMPFILE2"
	return 0
}

Make_boot_flop()
{
	if [ -f $VARMERGE/winboot.dsk ]
	then
		# When someone has put in this file, we are to
		# use it and bypass the bootstrap method.
		# This file is not there by default.
		Log $VARMERGE/winboot.dsk exists
		Echo
		Echo "Using file $VARMERGE/winboot.dsk for mini DOS install."
		Echo
		cp $VARMERGE/winboot.dsk $VARMERGE/bootflop.dsk 
		cmp -s $VARMERGE/winboot.dsk $VARMERGE/bootflop.dsk 
		if [ $? -ne 0 ]
		then
			Echo "Failed to create temporary file"
			Echo "$VARMERGE/bootflop.dsk"
			Echo "Cannot install."
			Exit $EX_CREATE_FAIL
		fi
		# OK!
		return
	fi
	# Now try to create boot floppy from bootable media.
	DDCMD=/bin/dd
	DOS7DBR="$STATICMERGE"/bs/dos7.dbr
	TF1="$VARMERGE"/tmp/user_flop_t1
	BFLOP="$VARMERGE"/bootflop.dsk
	touch "$BFLOP" 2> /dev/null
	if [ ! -f "$BFLOP" ]
	then
		Echo Cannot create $BFLOP
		Exit $EX_CREATE_FAIL
	fi

	rm -f "$TF1"
	case "_$DID_MOUNT" in
	_mount_cd)
		Log "Try to extract bootable stuff from CD"
		# Try to extract a boot floopy from a bootable CD ROM
		"$STATICMERGE"/bin/torito -i "$MERGE_CD_DEV_NAME" -o "$TF1"
		RETVAL=$?
		if [ $RETVAL -eq 0 ]
		then
			Echo "Found bootable CD-ROM. Extracting boot image ..."
			"$DDCMD" if="$DOS7DBR" of="$BFLOP" 2>/dev/null
			"$DDCMD" if="$TF1" of="$BFLOP" bs=512 skip=1 seek=1 \
				  2>/dev/null
			rm "$TF1"
			mv "$BFLOP" "$VARMERGE"/bootflopA.dsk 
			ClearFloppyImage "$VARMERGE"/bootflopA.dsk 
			[ $? -eq 0 ] && return
			# Failed!
			rm -f "$VARMERGE"/bootflopA.dsk 
		fi
		# Failed!
		rm -f "$TF1"
		;;
	_mount_dosc)
		Log "Make boot floppy from DOS boot drive."
		# Create boot floopy from a bootable DOS volume.
		# The volume is mounted at $VARMERGE/mnt/loadwin
		OLD_DIR=`pwd`
		cd "$VARMERGE"/mnt/loadwin
		ls  > "$TF1"
		FN1=`grep -i ^io.sys "$TF1"`
		[ "x$FN1" = "x" ] && FN1=`grep -i ^winboot.sys "$TF1"`
		FN2=`grep -i ^command.com "$TF1"`
		FN3=`grep -i /sys.com "$TF1"`
		FN4=`grep -i /format.com "$TF1"`

		if [ "x$FN1" != "x" -a "x$FN2" != "x" ]
		then
			# IMPORTANT NOTE:
			# The virtual disks have a 512 byte header
			# that must be skipped over to get to the
			# effective start of the floppy image.
			cp "$STATICMERGE"/diskimages/f.dsk "$BFLOP"
			chmod +w "$BFLOP"
			# Insert the "DOS 7 boot record, which is 512 bytes.
			# NOTE: Syntax of dd
			#   skip: skip blocks at start of input
			#   seek: skip blocks at start of output
			"$DDCMD" if="$DOS7DBR" \
				of="$BFLOP" bs=512 seek=1 count=1
			"$DDCMD" if="$STATICMERGE"/diskimages/f.dsk \
				of="$BFLOP" bs=512 skip=2 seek=2 
			echo "copyto io.sys $FN1" \
				| $STATICMERGE/dosdisk -s "$BFLOP"
			echo "copyto command.com $FN2" \
				| $STATICMERGE/dosdisk -s "$BFLOP"
			[ "x$FN3" != "x" ] && echo "copyto sys.com    $FN3" \
				| $STATICMERGE/dosdisk -s "$BFLOP"
			[ "x$FN4" != "x" ] && echo "copyto format.com $FN4" \
				| $STATICMERGE/dosdisk -s "$BFLOP"
			echo dir | "$STATICMERGE"/dosdisk -s "$BFLOP" > "$TF1"
			FOO=`grep command.com "$TF1"`
			BAR=`grep io.sys "$TF1"`
			rm -f "$TF1"
			if [ "x$FOO" != "x" -a "x$BAR" != "x" ]
			then
				mv "$BFLOP" "$VARMERGE"/bootflopA.dsk 
				# OK!
				cd "$OLD_DIR"
				return
			fi
			Log "Failed to create the boot floppy!"
		else
			Log "Did not find io.sys(winboot.sys) or command.com"
		fi
		cd "$OLD_DIR"
		# Failed!
		rm -f "$TF1"
		;;
	esac
	# Failed to create boot floppy from CD or native DOS volume.
	
	rm -f "$BFLOP"
	Log "Run user_floppy.sh to get a boot floppy image."
	# The following creates bootflop.dsk from the user supplied floppy.
	#SRI
	#sh $STATICMERGE/bin/user_floppy.sh 
	# this variable will contain something like "sri_floppy_dev /dev/fd0" or
	# "sri_floppy_file /path/to/floppyfile", set in the env when the
	# SRI runs ths script
	Log "running $STATICMERGE/bin/user_floppy.sh $SRI_FLOPPY_ARGS"
	sh $STATICMERGE/bin/user_floppy.sh $SRI_FLOPPY_ARGS
	#ENDSRI
	RET_VAL=$?
	if [ $RET_VAL -ne 0 -o ! -s $VARMERGE/bootflop.dsk ]
	then
		Echo "Unable to continue install."
		Echo "You must have a valid DOS boot floppy"
		Echo "before you can again try to install the"
		Echo "DOS from the Windows CD or boot drive."
		rm -f $VARMERGE/bootflop.dsk
		Exit $EX_CREATE_FAIL
	fi
	# Rename to bootflopA.dsk so we know that it is one
	# we created.  (So it is ok to remove as needed.)
	mv $VARMERGE/bootflop.dsk $VARMERGE/bootflopA.dsk 

}

# Make sure to not use any created boot disks from
# an earlier installation attempt.
# -- bootflop.dsk and bootflopA.dsk are temporary files.
rm -f $VARMERGE/bootflop.dsk $VARMERGE/bootflopA.dsk

if [ ! -f $VARMERGE/dosroot/dos/version.dos ]
then
	Make_boot_flop
fi

Echo Copying the Windows files.
cd $WIN9x_DIR
#SRI
SRI_NUM_PLUS=0
for i in *
do
	[ ! -f $i ] && continue
	SRI_NUM_PLUS=`expr $SRI_NUM_PLUS + 1`
done
Log "I got SRI_NUM_PLUS = $SRI_NUM_PLUS"
#ENDSRI

#SRI
SRI_PLUS_SHARE=25
SRI_COUNTER=0
	SRI_TMP_TOP=0
SRI_TOTAL_PROGRESS=25
SRI_CURRENT_PROGRESS=0
#ENDSRI
for i in *
do
	[ ! -f $i ] && continue
	LowerCase=`echo $i | tr '[:upper:]' '[:lower:]' `
#SRI
# progress output here
	SRI_COUNTER=`expr $SRI_COUNTER + 1`
	SRI_TMP_TOP=`expr $SRI_COUNTER \* $SRI_PLUS_SHARE`
	SRI_CURRENT_PROGRESS=`expr $SRI_TMP_TOP / $SRI_NUM_PLUS`
	SRI_report_progress `expr $SRI_TOTAL_PROGRESS + $SRI_CURRENT_PROGRESS`
#ENDSRI
	ECHOE "+\c"
	Log $i
	cp $i "$CAB_DIR/$LowerCase"
	if [ ! -f "$CAB_DIR/$LowerCase" ]
	then
		Echo
		Echo Failed to copy file $i
		Echo Out of Space?
		Exit $EX_CREATE_FAIL
	fi
done
#SRI
SRI_CURRENT_PROGRESS=0
SRI_TOTAL_PROGRESS=`expr $SRI_TOTAL_PROGRESS + $SRI_PLUS_SHARE`

#ENDSRI

Echo

if [ -d ols ]
then
	Echo "Copying the Online Services subdirectory."
	find ols -type d -print | cpio -pdmu $CAB_DIR >> $LOGFILE 2>&1
	find ols -type f -print | while read FILE ; do
		echo "$FILE" | cpio -pdmu $CAB_DIR >> $LOGFILE 2>&1
		ECHOE "+\c"
	done
	Echo
fi

cd "$CAB_DIR"

Unmount_NOW
TMPDIR="$CAB_DIR/tmp"
mkdir $TMPDIR
if [ ! -d $TMPDIR ]
then
	Echo "Unable to create temporary directory: $TMPDIR"
	Echo "Exiting..."
	Log "Returning value $EX_CREATE_FAIL"
	Exit $EX_CREATE_FAIL
fi
if   [ "$FOUND_WIN95" = "yes" ]; then
	FIRST_CAB=`echo win95_*.cab | cut -f1 -d' '`
elif [ "$FOUND_WIN98" = "yes" ]; then
	FIRST_CAB=`echo win98_*.cab | cut -f1 -d' '`
elif [ "$FOUND_WINME" = "yes" ]; then
	# First check for a single digit numbered cab file.
	FIRST_CAB=`echo win_?.cab | cut -f1 -d' '`
	[ ! -f "$FIRST_CAB" ] && FIRST_CAB=`echo win_*.cab | cut -f1 -d' '`
fi
Log "FIRST_CAB=$FIRST_CAB"
cd $DOSI_DIR

# When a DOS is not currently installed then do a boot strap off of
# the special special virtual boot floppy.
if [ ! -f $VARMERGE/dosroot/dos/version.dos ]
then
	# Create empty files with the user as the owner in a restricted
	# (own by root) directory so that the user can write to these files.
	$STATICMERGE/dos7utils -t			>> $LOGFILE 2>&1

	if [ -f $VARMERGE/bootflop.dsk ]
	then
		# When someone has put in this file, we are to
		# use it and bypass the bootstrap method.
		# This file is not there by default.
		cp $VARMERGE/bootflop.dsk "$CAB_DIR/b.dsk"
	elif [ -f $VARMERGE/bootflopA.dsk ]
	then
		# This was created from the user's boot floppy.
		# It is only there if the user supplied some bootable media,
		# and the script "user_floppy.sh" was used to make this
		# boot floppy.  Refer to the call to user_floppy.sh above.
		cp $VARMERGE/bootflopA.dsk "$CAB_DIR/b.dsk"
	else
		# This should not happen because we should have previously
		# aborted if there was no boot floppy image.
		Echo "Cannot install because there is no boot floppy image available".
		Exit $EX_CREATE_FAIL
		
	fi

	cp "$CAB_DIR/b.dsk" "$TMPDIR/tmp.dsk"
	$COMPRESS < $TMPDIR/tmp.dsk > ${VERNAME}.dsk.${CEXT}
	rm -f $TMPDIR/tmp.dsk

	echo "# Virtual install disks for MS-DOS 7/8"	>  ${VERNAME}.vdl
	echo "DISKCOUNT=1"				>> ${VERNAME}.vdl
	echo "DISK1=$VERNAME.dsk"			>> ${VERNAME}.vdl

	# Create ms7.set
	# Describes the MS-DOS 7 installation parameters for virtual disks.
	#  MENULINE	This is what appears on the menu.
	#  EMSGNAME	This is what is use for the name in an error message.
	#  FUNCFILE	This is the file name of the ".func" file.
	#  VDLFILE	This is the name of the ".vdl" file, which contains a
	#		list of	all the virtual disks.
	if [ "$FOUND_WINME" = "yes" ]; then
		echo 'MENULINE="MS-DOS 8 "'		>  ${VERNAME}.set
		echo 'EMSGNAME="MS-DOS 8"'		>> ${VERNAME}.set
		echo "FUNCFILE=ms8x.func"		>> ${VERNAME}.set
	else
		echo 'MENULINE="MS-DOS 7 "'		>  ${VERNAME}.set
		echo 'EMSGNAME="MS-DOS 7"'		>> ${VERNAME}.set
		echo "FUNCFILE=ms7x.func"		>> ${VERNAME}.set
	fi
	echo "VDLFILE=$VERNAME.vdl"			>> ${VERNAME}.set

	Echo "Set locale info for current system."
 	$STATICMERGE/dos7utils -f replace

	Echo "Pre-Installation Phase: Installing minimal DOS system..."
	$STATICMERGE/dos7utils -m
	RETVAL=$?
	# relock since dosinstall remove the lock file.
	$STATICMERGE/dos7utils -l			>> $LOGFILE 2>&1

	# remove the *$VERNAME* files.
	$STATICMERGE/dos7utils -c

	if [ $RETVAL -ne 0 ]
	then
		cd $DOSI_DIR
		rm -rf $TMPDIR
		Echo "Error: Minimal automatic pre-installation of DOS7 failed."
		Exit $EX_NO_DOS
	fi
	Echo "Pre-Installation Phase: Completed."
fi

# Create empty DOS 7 files with the user as the owner so we have
# write permission
Log "Create empty DOS 7 files in $DOSI_DIR"
$STATICMERGE/dos7utils -t				>> $LOGFILE 2>&1

export TOOLDIR WIN9x_DIR LOGFILE VERNAME

A_DSK=$TMPDIR/tmp.dsk
B_DSK=$TMPDIR/${VERNAME}.dsk
rm -f $A_DSK

cp $STATICMERGE/diskimages/f.dsk $A_DSK
chmod +w $A_DSK
cp $A_DSK $B_DSK

Echo


cd "$CAB_DIR"
echo "WINDOWS_VERSION=$WINDOWS_VERSION" > info.txt
chmod 444 info.txt
# NOTICE: the WINDOWS_VERSION variable in installwindows.sh and 
#	  the Win95VersionInfo[].w9x_VerName should use the same
#	  value as here!!!
# The possible WINDOWS_VERSION settings:
# 95osr2, 95classic, 98se, 98sezhcn, 98sezhtw, 98sekr, 98sejp, 98orig, 9xme
case $WINDOWS_VERSION in
95*)
	Echo "Installing MS-DOS files from Windows95 CD-ROM files."
        PRECOPY_CAB=precopy1.cab
	cat $TOOLDIR/ms7sys.bat \
                | sed -e "s/Precopy.cab/$PRECOPY_CAB/g" \
		| sed -e "s/First.cab/$FIRST_CAB/g" \
		| sed -e "s/REM WIN95 //g" \
		> $TMPDIR/ms7sys.bat
	;;
98*)
	Echo "Installing MS-DOS files from Windows98 CD-ROM files."
	WINBOOT_CAB=base5.cab
        if [ "$WINDOWS_VERSION" = "98sezhcn" ]
        then
             DRVSPACE_CAB=base5.cab
             PRECOPY_CAB=precopy2.cab
        elif [ "$WINDOWS_VERSION" = "98sejp" ]
	then
	     WINBOOT_CAB=base6.cab
             DRVSPACE_CAB=base5.cab
             PRECOPY_CAB=precopy2.cab
	else
	     # 98sezhtw and 98sekr are same as 98se here
             DRVSPACE_CAB=base4.cab
             PRECOPY_CAB=precopy1.cab
        fi
        cat $TOOLDIR/ms7sys.bat \
                | sed -e "s/Precopy.cab/$PRECOPY_CAB/g" \
		| sed -e "s/First.cab/$FIRST_CAB/g" \
		| sed -e "s/Winboot.cab/$WINBOOT_CAB/g" \
		| sed -e "s/Drvspace.cab/$DRVSPACE_CAB/g" \
		| sed -e "s/REM WIN98 //g" \
		> $TMPDIR/ms7sys.bat
	;;
9xme)
	Echo "Installing MS-DOS files from Windows ME CD-ROM files."
	WINBOOT_CAB=precopy1.cab
	DRVSPACE_CAB=precopy1.cab
        PRECOPY_CAB=precopy1.cab
	cat $TOOLDIR/ms7sys.bat \
                | sed -e "s/Precopy.cab/$PRECOPY_CAB/g" \
		| sed -e "s/First.cab/$FIRST_CAB/g" \
		| sed -e "s/Winboot.cab/$WINBOOT_CAB/g" \
		| sed -e "s/Drvspace.cab/$DRVSPACE_CAB/g" \
		| sed -e "s/REM WIN98 //g" \
		> $TMPDIR/ms7sys.bat
	;;
*)
	# This cannot happen, but if someone screws up the script,
	# we need to protect ourselves by bailing early so
	# that the problem can be found quickly.
	Echo "Internal error #2 in installwindowsCD: $WINDOWS_VERSION"
	exit $EX_BIZZARE
	;;
esac
Echo " "


case $WINDOWS_VERSION in
9xme)
    # For WinME we can't use the "sys" command so we just have to
    # live with the boot floppy that we were given.
    Log "WinME case: copying $CAB_DIR/b.dsk to $B_DSK"
    cp $CAB_DIR/b.dsk $B_DSK
    ;;

*)
    # Create a bootable virtual floppy on drive B, using the DOS from
    # the Win95/98 CD.  The ms7sys.bat batch files does this by running
    # "extract" to get winboot.sys, command.com, and sys.com, and then
    # running this "sys" command to make drive B bootable.
    # (The dos session must be in the current directory so must use -r)
    $DOSWINBINDIR/dos +b -e -r +aa:=$A_DSK +ab:=$B_DSK \
    	+p$TMPDIR/ms7sys.bat $KOPT ver >> $LOGFILE 2>&1
    ;;
esac

    cd $TMPDIR
    rm -f $A_DSK
    # Check the virtual floppy to make sure that it actually was
    # correctly made.
$DOSWINBINDIR/dos +b -e -p -r -t $KOPT +aa:=$B_DSK dir a: | grep -i command >> $LOGFILE 2>&1
if [ $? -ne 0 ]
then
	Echo "Error, failed to extract the DOS system files."
	cd $DOSI_DIR
	rm -rf $TMPDIR
	Log "Returning value $EX_CREATE_FAIL"
	Exit $EX_CREATE_FAIL
fi

Log "Using dosdisk to rename winboot.sys to io.sys in $B_DSK"

echo "rename winboot.sys io.sys" | \
	$STATICMERGE/dosdisk -s $B_DSK >> $LOGFILE 2>&1

Log "Now $B_DSK is a bootable DOS 7/8 virtual floppy."

Log "Creating ${B_DSK}.${CEXT}"

$COMPRESS < $B_DSK > $DOSI_DIR/${VERNAME}.dsk.${CEXT}		2>> $LOGFILE
if [ ! -s $DOSI_DIR/${VERNAME}.dsk.${CEXT} ]
then
	Echo "Error, failure to properly create $DOSI_DIR/${VERNAME}.dsk.${CEXT}"
	cd $DOSI_DIR
	rm -rf $TMPDIR
	Log "Returning value $EX_CREATE_FAIL"
	Exit $EX_CREATE_FAIL
fi
rm -f $B_DSK

cd "$CAB_DIR"
LIST=`ls *.cab`

cd $TMPDIR
rm -rf dosfiles
mkdir dosfiles
if [ ! -d dosfiles ]
then
	Echo "Unable to create temporary directory: $TMPDIR/dosfiles"
	Echo "Exiting..."
	Log "Returning value $EX_CREATE_FAIL"
	Exit $EX_CREATE_FAIL
fi
cd $TMPDIR/dosfiles
for i in $LIST
do
	ln -s "$CAB_DIR/$i" $i
done

ln "$CAB_DIR/extract.exe" extract.exe
Echo "Now extracting the DOS files."

# Need to keep the DOS command line under 128 characters
L1="ansi.sys attrib.exe chkdsk.exe choice.com country.sys debug.exe defrag.exe"
L2="deltree.exe diskcopy.com display.sys doskey.com edit.com edit.hlp ega.cpi"
L3="fc.exe fdisk.exe find.exe format.com iso.cpi keyb.com keyboard.sys"
L4="keybrd2.sys label.exe mem.exe mode.com more.com move.exe mscdex.exe"
L5="nlsfunc.exe ramdrive.sys scandisk.ini setver.exe share.exe sort.exe"
L6="start.exe subst.exe sys.com xcopy.exe xcopy32.exe xcopy32.mod ndis.vxd"
L7="ftp.exe telnet.exe telnet.hlp kernel32.dll hypertrm.dll"

XDIR=$TMPDIR/x
mkdir $XDIR
mkdir $XDIR/xlists
mkdir $XDIR/clists
Log "Extract the directory listings from all the cab files."
[ -f "$CAB_DIR/cablists"   ] && rm -f "$CAB_DIR/cablists"
[ ! -d "$CAB_DIR/cablists" ] && mkdir "$CAB_DIR/cablists"
chown bin "$CAB_DIR/cablists"
chgrp bin "$CAB_DIR/cablists"
chmod 775 "$CAB_DIR/cablists"
rm -f "$CAB_DIR/cablists/"*.cab.txt
sh $STATICMERGE/bin/makecablists "`pwd`" "$CAB_DIR/cablists"

Log Find which files are in which cabs

#SRI
# progress output here
#ENDSRI

Echo ".\c"
cd "$CAB_DIR/cablists"
for i in $L1 $L2 $L3 $L4 $L5 $L6 $L7
do
	grep  -l " ${i}" *.cab.txt \
		| sed -e "s/cab.txt/cab/g" > $XDIR/clists/$i
	CNT="`cat $XDIR/clists/$i | wc -l`"
	if [ $CNT -eq 0 ]
	then
		Log "WARNING, $i not in the cab files"
	elif [ $CNT -gt 1 ]
	then
		Log "WARNING, $i listed in $CNT cab files!"
		cat $XDIR/clists/$i >> $LOGFILE
	fi
done
cd $XDIR

Log Just for the files we are interested in, make lists of
Log which files are in which cab files.
Echo ".\c"
cd $XDIR/clists
CAB_LIST=`grep -h cab *.* | sort | uniq`
if [ -z "$CAB_LIST" ]
then
	Echo "Error, cannot find appropriate CAB files to install from."
	cd $DOSI_DIR
	rm -rf $TMPDIR
	Log "Returning value $EX_CREATE_FAIL"
	Exit $EX_CREATE_FAIL
fi
for i in $CAB_LIST
do
	grep -l $i *.* > $XDIR/xlists/$i
done

# When running the DOS 7.1 extract program, the DOS TMP environment
# variable must be set to where temporary files can be created,
# otherwise it tries to use the root of the J drive for temporary files.
BATFILE=$CDIR/a$$.bat
ECHOE "set TMP=c:\\" | $STATICMERGE/charconv -p -x > $BATFILE
Start_New()
{
	ECHOE "Echo '.\\\c'" >> $2
	#SRI
	if [ -n "$SRI_FROM_GUI" ]
	then
		SRI_COUNTER=`expr $SRI_COUNTER + 1`
		SRI_TMP_TOP=`expr $SRI_COUNTER \* $SRI_DOT_SHARE`
		SRI_CURRENT_PROGRESS=`expr $SRI_TMP_TOP / $SRI_NUMDOTS`
		SRI_TOTAL_PROGRESS=`expr $SRI_PRE_DOT_PROGRESS + $SRI_CURRENT_PROGRESS`
		ECHOE "SRI_report_progress $SRI_TOTAL_PROGRESS" >> $2
	fi
	#ENDSRI
	# The dos sessions must be in the current directory so must use -r.
	# Note: Do NOT add to the following without adjusting the
	#       length calculations in the loop below.
	ECHOE "Log \`date\`" >> $2
	ECHOE "$DOSWINBINDIR/dos +b -e +p$BATFILE -r -t $KOPT extract /Y /L . $1 \c" >> $2
}

Log Now create a UNIX script with the dos commands to extract the files.
Echo ".\c"
cd $XDIR/xlists
ZZ=$TMPDIR/dosfiles/doit.sh
#SRI
if [ -n "$SRI_FROM_GUI" ]
then
	SRI_NUMDOTS=0
	for i in *.cab
	do
		SRI_NUMDOTS=`expr $SRI_NUMDOTS + 1`
		SRI_ROW_LENGTH=0
		for j in `cat $i`
		do
			#how about: SRI_LENGTH=`expr length "$j"`
			SRI_TMP_LENGTH=`echo "${j}"  | wc -c`
			SRI_ROW_LENGTH=`expr $SRI_ROW_LENGTH + $SRI_TMP_LENGTH`
		done

		# extra dots come for every time the file list wraps 85
		SRI_ROW_DOTS=0
		SRI_ROW_DOTS=`expr $SRI_ROW_LENGTH / 85`
		SRI_NUMDOTS=`expr $SRI_NUMDOTS + $SRI_ROW_DOTS`
	done

	Log "SRI: calculated $SRI_NUMDOTS dots" 
	SRI_DOT_SHARE=25
	SRI_PRE_DOT_PROGRESS=$SRI_TOTAL_PROGRESS
	SRI_COUNTER=0
fi
#ENDSRI
for i in *.cab
do
	LINE=""
	for j in `cat $i`
	do
		LEN1=`echo "$LINE" | wc -c`
		LEN2=`echo "${j}"  | wc -c`
		TLEN=`expr $LEN1 + $LEN2`
		# The DOS command line is somewhat limited in length,
		# (128 total bytes), so test here to see if we need to
		# issue more than one extract on this cab file.
		# There are two extra bytes for control info that reduce
		# the availabe bytes for the actual command to 126.
		# Then dosexec uses up some bytes for command.com parameters
		# to set the environment size and use the "/c" command.
		# So the command line we execute will turn out to be
		# "/e:512/c  extract /Y /L . win95_xx.cab "
		# followed by the list of files.  The first part of the
		# command string is (count it) 39.  The total line must
		# fit into 126 bytes, so 126-39=87.  If we pass command.com
		# a command line that is too long, it ignores it and
		# puts up a standard DOS prompt.  This is bad if stdout
		# is redirected to /dev/null or to a file because it will
		# just hang waiting for a command to be typed which will
		# never come.  So actually place the limit a bit lower
		# to give a little bit of margin.
		# 
		if [ $LEN1 -lt 3 -o $TLEN -gt 85 ]
		then
			echo "$LINE >> $LOGFILE 2>&1" >> $ZZ
			Start_New $i $ZZ
			LINE="${j}"
		else
			LINE="$LINE ${j}"
		fi
	done
	echo "$LINE >> $LOGFILE 2>&1" >> $ZZ
done

if [ "x$TRACE" = "xtrace" ]
then
	rm -rf $VARMERGE/tmp/tracedosinst
	[ ! -d $VARMERGE/tmp/tracedosinst ] && mkdir $VARMERGE/tmp/tracedosinst
	[ ! -d $VARMERGE/tmp/tracedosinst/x ] && mkdir $VARMERGE/tmp/tracedosinst/x
	mv $XDIR/* $VARMERGE/tmp/tracedosinst/x
fi
cd $TMPDIR
rm -rf $XDIR

cd $TMPDIR/dosfiles
Log Running the script to extract the files.

#SRI
# progress output here
#ENDSRI

Echo "."
. $ZZ
#SRI
#just to make sure, in case something is screwey with the calculations
#(it would be better to check, then report an error if there was)
if [ -n "$SRI_FROM_GUI" ]
then
	SRI_TOTAL_PROGRESS=`expr $SRI_PRE_DOT_PROGRESS + $SRI_DOT_SHARE`
	SRI_report_progress $SRI_TOTAL_PROGRESS
fi
#ENDSRI
Log "`date`"
rm -f $BATFILE
Echo
Echo "Finished extracting the DOS files."

[ "x$TRACE" = "xtrace" ] && cp $ZZ $VARMERGE/tmp/tracedosinst
[ "x$TRACE" = "xtrace" ] && ls -lL *.cab > $VARMERGE/tmp/tracedosinst/ls_cab.out

rm -f $ZZ *.cab
[ "x$TRACE" = "xtrace" ] && ls -l > $VARMERGE/tmp/tracedosinst/ls_file.out

Log "DOS files extracted into directory `pwd`"

# Some files need to be saved in the $CAB_DIR directory.
# (See fixWin95SymLinks)
for i in ndis.vxd ftp.exe telnet.exe telnet.hlp kernel32.dll hypertrm.dll
do
	[ -f $i ] && cp $i $CAB_DIR
done

Log "Creating ${VERNAME}.cpio.${CEXT}"
ls | cpio -ov$CPIO_TYPE  > tmpfile				2>> $LOGFILE
if [ ! -s tmpfile ]
then
	Echo "Error, failure to properly create the cpio file!"
	Echo "The files in the directory `pwd`"
	ls -lt
	cd $DOSI_DIR
	rm -rf $TMPDIR
	Log "Returning value $EX_CREATE_FAIL"
	Exit $EX_CREATE_FAIL
fi
$COMPRESS < tmpfile > $DOSI_DIR/${VERNAME}.cpio.${CEXT}	2>> $LOGFILE
RETVAL=$?
if [ ! -s $DOSI_DIR/${VERNAME}.cpio.${CEXT} ]
then
	Echo "Error, failure to properly create $DOSI_DIR/${VERNAME}.cpio.${CEXT}"
	Echo "Compress returned $RETVAL"
	cd $DOSI_DIR
	rm -rf $TMPDIR
	Log "Returning value $EX_CREATE_FAIL"
	Exit $EX_CREATE_FAIL
fi
cd $DOSI_DIR
rm -rf $TMPDIR

echo "# Virtual install disks for MS-DOS 7"	>  ${VERNAME}.vdl
echo "DISKCOUNT=1"				>> ${VERNAME}.vdl
echo "DISK1=$VERNAME.dsk"			>> ${VERNAME}.vdl
echo "UNIXCPIO=${VERNAME}.cpio"			>> ${VERNAME}.vdl

# Create ms7.set
# Describes the MS-DOS 7 installation parameters for virtual disks.
#  MENULINE	This is what appears on the menu.
#  EMSGNAME	This is what is use for the name in an error message.
#  FUNCFILE	This is the file name of the ".func" file.
#  VDLFILE	This is the name of the ".vdl" file, which contains a list of
#		all the virtual disks.
if [ "$FOUND_WINME" = "yes" ]; then
	echo 'MENULINE="MS-DOS 8 "'		>  ${VERNAME}.set
	echo 'EMSGNAME="MS-DOS 8"'		>> ${VERNAME}.set
	echo "FUNCFILE=ms8x.func"		>> ${VERNAME}.set
else
	echo 'MENULINE="MS-DOS 7 "'		>  ${VERNAME}.set
	echo 'EMSGNAME="MS-DOS 7"'		>> ${VERNAME}.set
	echo "FUNCFILE=ms7x.func"		>> ${VERNAME}.set
fi
echo "VDLFILE=$VERNAME.vdl"			>> ${VERNAME}.set
echo "FROMCD=fromCD"				>> ${VERNAME}.set

Log "Done coping the files in."
COPYCOMPLETED=completed

# Parameters used by Run_Dosinstall_Now:
#	VERNAME
#	STATICMERGE
#	VARMERGE
#	DOSI_DIR
# Returns with RETVAL set.
Run_Dosinstall_Now
RETVAL=$?
[ $RETVAL -eq 0 ] && Echo "Finished loading Windows files."
Log "`date`"
License_Query
Log "Returning value $RETVAL."
Exit $RETVAL
