#! /bin/sh
#
# JunOS 6.x install script
#
# Copyright (c) 2001-2003, Juniper Networks, Inc.
# All rights reserved.
#
# $Id: install,v 1.86 2003/11/18 21:42:12 dock Exp $
#
# Install a router
#    from some media (pcmcia, net, floppy)
#    to some media (flash, harddrive)
#


#
# If we're init, we run on the console (whatever that is). This code
# must be the first thing in this file, else the script will fail
# when it runs as init.
#
PATH=/sbin:/usr/sbin:/bin:/usr/bin
export PATH

if [ "$$" = 1 ] ; then
    if [ "$FIRSTPASS" = "" ] ; then
	if [ -f /etc/devfs ] ; then
	    /sbin/mount_devfs /mnt /dev
	fi
	FIRSTPASS=no
	export FIRSTPASS
	exec settty /dev/console $0 "$@"
    fi
    echo "Disabling watchdog"
    /sbin/watchdog -off
fi

case "$@" in
	*-s*)
		/bin/sh;
		exit 0 ;;
esac


# If you want the install to work quietly uncomment the following line
#
# INSTALL_QUIET=1

# If you want to enable tracing, uncomment the following lines. You
# will land up enabling set -x
#
# INSTALL_TRACE_ENABLED=1

# Set debug to "echo" to cause destructive commands to be displayed
# instead of executed. Do not use debug too liberally or you will
# not be able to get the script to do anything. Do not use it on
# commands that read stuff or mount partitions. It is best to do the 
# debugging in single user mode. 
# debug=echo

# If you wish to log all that happens during install into a logfile,
# then uncomment this line. The name of the logfile is given by the
# 'logfilename' variable. This is disabled in production because it is
# not perfect. Flaws include: debugging shell will not show a prompt,
# any signal to the installer will abort the installer,
# piped commands will split lines requiring some additional
# filtering (fixed), any question to the user must be echoed with a 
# newline (fixed), the log is not saved if the install fails. 
#
# INSTALL_LOG=1

# This is the re name that has to always be displayed for the user.
re_name=""

# this is the name of the flashdrive. It is set once the model we are running
# on is recognized. This variable will be not be set on an olive.
flashdrive=""

# this is the size of the flash drive if it is present
flash_drive_size=""

# this is the name of the harddrive. It is set once the model we are running
# on is recognized. This variable must be set for all models. The
# install script will bail if it is not.
harddrive=""

# if the hard drive is not present during install this variable is set to
# "No"
harddrive_present="Yes"

# This is used to find the install packages.  If we booted from ls120 or pcmcia
# this will contain the boot device.   For floppy (ie: olive) and jinstall's,
# packagefsdev will be blank.
packagefsdev=""

# Drives on which to do the install. This is setup in
# discover_install_drives
installdrive=""

# Set to 'pccard' 'ls120' or 'floppy' if this is a media install. This
# is set by the discover_install_drive routine
media_install=""

#
# Set to 'yes' if this is an install on a J20 - GGSN
#
ggsn_install=""

#
# Sizes of root filesystems. The min_rootsize is set to the value
# that many disks had prior to 5.0.  For 5.X jinstall, root size was
# default_50_rootsize.  For 6.X that will remain for the smallest
# disks (<80M); for flash drives 80M to 120M in size, config gets
# 12M and root gets the rest; flash drives >120M config gets 10%
# of disk size and root gets the rest. GGSN installs used to be
# special to allocate a larger root; with 6.0, all installs will
# allocate a larger root for larger sized flash drives.
#
min_rootsize=133120
min_configsize=20480
default_50_rootsize=135680
default_60_configsize=24576
rootsize_122=225764
configsize_122=25084

# this is the disk suffix and refers to the slice number
dsuffix=s1;

# used to size swap space later, swapsize = 2 * memsize
memsize=`sysctl -n hw.512bmem`;

# the /tmp partition is limited based on the size of the memory
# available. The size is in sectors
tmpsize=196608

# the tmpvarsize is used to size the MFS mounted on /mnt/var. This MFS
# is used when the hard disk is missing. The size is in sectors.
tmpvarsize=270336

# Directory where the preinstall stage of the bootstrap installer puts
# information. The bootstrap installer puts things in
# /var/tmp/preinstall, and /var is the f partition on the hard drive.
preinstalldir="tmp/preinstall"

# New location where the bits are kept. This is set by the
# mount_os_bundle or copy_os_bundle.
installdir="/${preinstalldir}"

# File in which things are recorded by the preinstall stage of the
# bootstrap installer. 
install_config="install.conf"

# The current offset in the disk, used for partitioning. This is used
# as a global variable by makepart. It my be initialized to zero
# every time a new drive is partitioned.
offset=0;

# directories that must exist in /var. It is used by setup_var.
var_dirlist="bin crash cron cron/tabs db db/config etc etc/filters home log run sw sw/pkg tmp"

# The name of the base OS package. This is set when sources the
# install_config file in discover_install_drive.
ospackage=""

# The edition of the ospackage (export or domestic). It is written
# into the +COMMENT and +DESC files for jbase. This variable is set
# when we source the install_config file in discover_install_drive
osedition=""

# The release number of the ospackage. Same as above. This variable is set
# when we source the install_config file in discover_install_drive
osrelease=""

# The name of the configs package. This is set when sources the
# install_config file in discover_install_drive. 
configpackage=""

# The list of packages in the install media (either the pc card or the 
# preinstall directory. This is set by the verify_*_package routines
packlist=""

# If set, means that we are doing a 4.x to 5.x upgrade. It is set by
# the mount_os_bundle and copy_os_bundle routines by differentiating 
# between the names of the ospackage jboot (means 5.0) vs jos-pre50
# (means 4.x).
isupgrade=""

# These are two secondary mount points for us to mount things. They
# are guaranteeded to be there on the memory-mapped root image that
# we boot on in addition to mnt.  
instrootmnt=/instrootmnt
packagemnt=/packagemnt

# The logfile in which to store the install logs
logfilename="install.log"

#
# subsh
#
# A debug subshell that the install script falls to whenever there is an error
#
subsh() {
    echo "You are now in a debugging subshell (you may not see a prompt)..."
    /bin/sh
    rv=`expr $? - 128 \> 0`
    if [ $rv = 1 ] ; then
	if [ ! -z "$INSTALL_LOG" ] ; then
	    save_install_log
	fi
	echo "Rebooting..."
	$debug /sbin/reboot
	while : ; do 
	done
    fi
}

warn() {
    if [ -z "$1" ]; then
	echo ""
    else
	echo "WARNING:" "$*"
    fi
}

warn_abort() {
    warn
    warn "This installation attempt will be aborted. You are now"
    warn " in a debug shell. Type ^D to reboot the system"
    subsh
}

notice() {
    if [ -z "$1" ]; then
	echo ""
    else
	echo "NOTICE:" "$*"
    fi
}

inform() {
    if [ -z "$INSTALL_QUIET" ]; then
	echo "$*"
    fi
}

error() {
    if [ -z "$1" ]; then
	echo ""
    else
	echo "ERROR:" "$*"
	subsh
    fi
}

trace() {
    if [ ! -z "$INSTALL_QUIET" ]; then
	echo "trace:" "$*"
    fi
}

mkempty() {
    if [ "$debug" != "" ] ; then
	echo "> $1"
    else
	> $1
    fi
}

#
# Read a string from the user.
#
getstring() {
    [ ! -z "$INSTALL_TRACE_ENABLED" ] && set +x
    while :
    do
	echo "${1}? ";
	read a;
	case "$a" in
	    !shell)
		subsh ;;
	    *)
		eval $2=\"$a\";
		break;
	 esac
    done
    [ ! -z "$INSTALL_TRACE_ENABLED" ] && set -x
}



#
# media_prompt_user
# 
# On a media install prompt the user if they wish to continue so
# that they have a chance to bail out. Else a PC card stuck in the
# router could wipe out their software. 
#
media_prompt_user() {
    while :
    do
	warn "The installation will erase the contents of your disks."
	getstring "Do you wish to continue (y/n)" response
	case "$response" in
	    [Yy]*)
		return
		;;
	    [Nn]*)
		$debug /sbin/reboot
		while : ; do 
		done
		;;
	    *)
		echo "y or n, please"
		;;
	 esac
    done
}




#
# mount_partition <drive> <partition> <mountpoint> fatal|nonfatal
#
# Will mount the root partition of a drive onto the given mount
# point. It will also unmount the existing filesystem on the
# mountpoint. If the drive is null, the mount will not occur but the
# umount will.
#
mount_partition() {

    if [ ! -d $3 ] ; then
	error "mount_partition: Mountpoint $3 does not exist"
    fi

    umount $3 > /dev/null 2>&1

    if [ "$1" != "" ] ; then
	mount /dev/${1}${dsuffix}${2} $3 
    	if [ $? != 0 -a "$4" = "fatal" ] ; then
	    error "mount_partition: Mount /dev/${1}${dsuffix}a $3 failed"
	fi
    else
	error "mount_partition: need a disk, partition=$2, mnt=$3"
    fi
}


#
# umount_partition <mountpoint>
#
umount_partition() {

    if [ ! -d $1 ] ; then
	error "umount_partition: Mountpoint $1 does not exist"
    fi

    umount $1 > /dev/null 2>&1
}


#
# mount_tmp <size> <mountpoint> limit
#
# Will create and mount an MFS filesystem at the mountpoint. The size
# of the MFS filesystem is given by size. If the create flag is set, 
# the directory will be created.
#
mount_tmp() {
    
    if [ ! -d "$2" ] ; then
	error "mount_tmp: Mountpoint $2 does not exist"
    fi

    umount $2 > /dev/null 2>&1

    #
    # size the tmp based on the amount of memory available. The formula is
    # Min(1/2 of memsize in "sectors" of 512B, 131072)
    #
    local available=$1
    if [ "$3" = "limit" ] ; then
	 available=`expr $memsize / 2`
	if [ $available -gt $1 ] ; then
	    available=$1
	fi
    fi

    $debug mount_mfs -T minimum -s $available /dev/null $2
    if [ $? != 0 ] ; then
	error "mount_tmp: failed when executing mount_mfs size=$available, mnt=$2"
    fi
}



#
# umount_tmp <mountpoint> delete
#
# Will unmount the MFS filesystem mounted at mountpoint and
# delete the mountpoint directory
#
umount_tmp() {

    if [ ! -d $1 ] ; then
	error "umount_tmp: Mountpoint $1 does not exist"
    fi

    umount $1
    if [ $? != 0 ] ; then
	error "umount_tmp: failed when executing umount mnt=$1"
    fi

    if [ "$2" = "delete" ] ; then
	$debug rm -rf $1
    fi
}
    

#
# mount_filesystem <rawdevice> <mountpoint> fatal|nonfatal
#
# Mount a filesystem on the mountpoint.
#
mount_filesystem() {

    if [ ! -d $2 ] ; then
	error "mount_filesystem: Mountpoint $2 does not exist"
    fi

    umount $2 > /dev/null 2>&1

    if [ "$1" != "" ] ; then
	mount $1 $2
    	if [ $? != 0 -a "$3" = "fatal" ] ; then
	    error "mount_filesystem: Mount $1 $2 failed"
	fi
    else
	error "mount_filesystem: need a rawdevice, mountpoint=$2"
    fi
}


#
# umount_filesystem <mountpoint>
#
umount_filesystem() {

    if [ ! -d $1 ] ; then
	error "umount_filesystem: Mountpoint $1 does not exist"
    fi

    umount $1 > /dev/null 2>&1
}




#
# preen_filesystems
#
# fsck drives so that there is a better change they mount without a
# problem. Even if some partitions do not exist, not harm done.
#
preen_filesystems() {

    if [ "$flashdrive" != "" ] ; then
	$debug fsck -p /dev/${flashdrive}${dsuffix}a > /dev/null 2>&1
	$debug fsck -p /dev/${flashdrive}${dsuffix}e > /dev/null 2>&1
    fi

    $debug fsck -p /dev/${harddrive}${dsuffix}a > /dev/null 2>&1
    $debug fsck -p /dev/${harddrive}${dsuffix}e > /dev/null 2>&1
    $debug fsck -p /dev/${harddrive}${dsuffix}f > /dev/null 2>&1
}


#
# setup_tmp <size> <mountpoint> <dir> <limit>
#
setup_tmp() {

    #
    # Need a temporary area to work in.
    #
    mount_tmp $1 $2 $4

    if [ "$3" != "" ] ; then
	#
	# create the directory
	#
	mkdir -p $3
	if [ $? != 0 ] ; then
	    error "setup_tmp: could not mkdir $3"
	fi
    fi
}
    

#
# setup_var
#
# Sets up the /var filesystem. It will mount it, check that the right
# directories are there, etc
#
setup_var() {

    local vardrive="/dev/${harddrive}${dsuffix}f"
    mount_filesystem $vardrive /mnt fatal

    for dir in $var_dirlist ; do 

	#
	# check if dir exists. If not create it
	#
	test -d "/mnt/$dir"
	if [ $? = 1 ] ; then
	    $debug rm -f /mnt/$dir
	    $debug mkdir /mnt/$dir
	    $debug chmod 755 /mnt/$dir
	fi

	#
	# check that the directory exists now, else error
	#
	test -d "/mnt/$dir"
	if [ $? != 0 ] ; then
	    error "setup_var: Unable to create $dir"
	fi
    done

    $debug chmod 4777 /mnt/tmp;

    umount_filesystem /mnt

}


#
# setup_nextbootdev
#
# Sets the next bootdev to the first drive listed in the installdrive
# variable 
#
setup_nextbootdev() {

    #
    # figure out the number if the flash drive and hard
    # drive. Basically convert wd0 or ad0 -> d0.
    #
    local flashnum=${flashdrive#[wa]}
    local hardnum=${harddrive#[wa]}

    if [ "$model" = "teknor" -o "$model" = "force" -o "$model" = "kontron" ] ; then
	for disk in $installdrive ; do
	    disk=${disk#[wa]}
	    if [ "$disk" = "$flashnum" ] ; then
		$debug sysctl -w 'machdep.nextbootdev=compact-flash'
		break
	    elif [ "$disk" = "$hardnum" ] ; then
		$debug sysctl -w 'machdep.nextbootdev=disk'
		break
	    fi
	done
	if [ $? != 0 ] ; then
	    warn "Could not set next boot device on host to $disk"
	fi
    elif [ "$model" = "cpv5000" ] ; then
	if [ -z "$media_install" ] ; then
	    $debug sysctl -w 'machdep.bootsuccess=2'
	    if [ $? != 0 ] ; then
		warn "Could not set next boot device on cpv5000 to $disk"
	    fi
	fi
    fi

    if [ ! -z "$media_install" ] ; then
	[ "$media_install" = "pccard" ] && umount $packagemnt
	getstring "Eject the installation media and hit [Enter] to reboot" response
    fi
}

# 
# flash_drive_read_label
# 
flash_drive_read_label() {
    local fl

    if [ -n "$flashdrive" ] ; then
	#
	# Read the current flash drive label,
	# if it exits, the flash drive is always ad0
	#
	fl=/tmp/flashlabeltmp$$
	disklabel -r $flashdrive > $fl 2>/dev/null
	if [ $? = 0 ] ; then
	    eval `awk ' / a:/ { print "frootsize="$2 }
			/ c:/ { print "fdisksize="$2 }
			/ e:/ { print "fconfigsize="$2 } '   < $fl`
	    flash_drive_size=$fdisksize
	    return
	fi
    fi

    #
    # couldn't read flash drive label
    #
    echo Could not read disklabel for $disk
    flash_drive_size=""
}

#
# initialize
#
# Initialize the environment
#
initialize() {

    #
    # if tracing is enabled, enable shell xtrace
    #
    [ ! -z "$INSTALL_TRACE_ENABLED" ] && set -x

    #
    #
    # setup signal handlers.
    #
    trap "" 0 1 2 3 15
    trap "error 'Aborting...'" 6

    #
    # print a banner
    #
    if [ -f /anim ] ; then
	dd if=/anim 2>/dev/null
    fi

    #
    # Attach our PCMCIA card, if there's one there.
    #
    if [ -x /usr/sbin/pccardd ] ; then
	$debug /usr/sbin/pccardd -z -d
    fi

    inform "Initialized the environment"
}


# write_install_log
#
# This guy reads lines and copies everything to a log file. It sends
# all lines except those from set -x to the screen. 
#
write_install_log() {
    local logfile="/tmp/$logfilename"       

    #
    # Disable shell xtrace. A common error is to set -x in this
    # process that is writing to the log file. stdout will get
    # unnecessarily cluttered. 
    #
    set +x

    if [ -z "$logfile" ] ; then
	error "write_install_log: need a logfile name, received null"
    fi

    #
    # create a log file and put an initial timestamp on it
    #
    awk 'END {print "Log started on ", strftime(), "\n" }' < /dev/null > $logfile
    if [ ! -f "$logfile" ] ; then
	error "write_install_log: unable to create $logfile"
    fi

    #
    # It is possible to do sneaky things here like sanitizing what
    # goes to the screen and cleaning up errors. I was an honest guy
    # but now I am tempted. Also note that long lines may get split up
    # and that causes set -x output to go to the screen.   
    #
    # Lines beginning with + are from shell tracing; lines beginning
    # with - and empty strings show up in some cases.
    #
    while read line
    do
	case "$line" in
	    +* | -* | "" | /tmp/preinstall/bin* ) 
		echo "$line" >> $logfile 
		;;
	    *)  
		echo "$line" >> $logfile
		echo "$line"
		;;
	esac
    done
}


# save_install_log
#
# Save the install log file in /var/log
#
save_install_log() {
    local logfile="/tmp/$logfilename"
    local varlogfile="/mnt/log/$logfilename"

    if [ "$harddrive_present" = "Yes" ] ; then
	#
	# mount the var filesystem
	#
	local varfilesystem="/dev/${harddrive}${dsuffix}f"
	mount_filesystem "$varfilesystem" /mnt nonfatal

	$debug cp $logfile $varlogfile
	if [ $? != 0 ] ; then
	    warn "Unable to copy $logfile to /var/log"
	fi
	awk 'END {print "\nLog saved on ", strftime() }' < /dev/null >> $varlogfile

	#
	# unmount var filesystem
	#
	umount_filesystem /mnt

	inform "Installer log saved in /var/log/$logfilename"
    else
	warn "Hard disk missing, unable to copy $logfile to /var/log"
    fi
}


#
# recognize_model
#
# recognize what machine model we are running on. Based on the model
# source some configuration files
#
recognize_model() {

    #
    # Try to figure out what model we are-- if the sysctl variable 
    # doesn't exist we're on an olive by De Factorum Jurisprudence.
    #
    re_name=`sysctl -n hw.re.name`
    model=`sysctl -n hw.re.model`
    model="${model:-olive}"
    inform "Routing engine model is $re_name"

    #
    # Read our model-specific script
    # This defines the media for that type of model, ie. the device names
    # for things like pcmcia, flashdrive, and harddrive.
    #
    local scriptdir
    scriptdir=`dirname $0`
    if [ -f "$scriptdir/$model" ] ; then
	inform "Sourcing $scriptdir/$re_name"
	. "$scriptdir/$model"
    fi

    #
    # harddrive cannot be null no matter what the model
    #
    if [ "$harddrive" = "" ] ; then
	error "recognize_model: Unable to discover hard drive"
    fi

    #
    # flash drive can be null in the case of an olive.
    #
    if [ "$flashdrive" = "" -a "$model" != "olive" ] ; then 
	error "recognize_model: Expected flash disk on model $re_name not found"
    fi

    inform "Discovered that flash disk = $flashdrive , hard disk = $harddrive"
}


#
# discover_install_drive
#
# Discovers the drive on which the installation should happen. Otherwise, 
# look for the drive which has the jinstall package and that is your 
# install drive.  
#
discover_install_drive() {

    installdrive=""

    # We want to install even if one of the two install target devices
    # (flashdrive or harddrive) is missing.  The following table shows
    # how the install procedure will behave if one of the install target
    # devices is missing.
    #  	_____________________________________
    #  	|installed    |   install targets   |
    #  	|   from media|  no HDD  |  no CF   |
    #  	-------------------------------------
    #  	|PCMCIA card  | succeeds | succeeds |
    #  	|LS120        | succeeds | succeeds |
    #  	|floppy       | fails    | succeeds |
    #  	|HDD(jinstall)| fails    | succeeds |
    #  	\-----------------------------------/

    #
    # Find out if we are booted off the PC card, LS120 or 1.44MB
    # floppy. If the media size is less than 2MB, then it is a
    # floppy. PC card and LS120 are treated the same way.
    # 
    if [ "$packagefsdev" != "" ] ; then
	mount -t cd9660 -r $packagefsdev $packagemnt
	if [ $? = 0 ] ; then
	    local space
	    space=`df -k $packagemnt | awk '$1 != "Filesystem"  {print $2}'`
	    if [ "$space" -lt 2048 ] ; then
		media_install="floppy"
	    else
		media_install="pccard"
	    fi	
	    umount $packagemnt
	fi
    fi	

    #
    # an alternate way of knowing if this is a floppy install is to
    # see if there is floppy signature file in the root filesystem
    #
    if [ -f "/FLOPPY" ] ; then
	media_install="floppy"
    fi

    #
    # The install happens on the flash drive AND the hard drive if it
    # is a media install. The order of drives is important - always put
    # flash ahead of the hard disk.
    #
    if [ "$media_install" != "" ] ; then
	# see what target devices are present (see table above)
	if [ "$media_install" = "floppy" ] ; then
	    dd if=/dev/$flashdrive of=/dev/null count=10 > /dev/null 2>&1
	    if [ $? != 0 ] ; then
		installdrive="$harddrive"
		warn "Compact-flash missing, installing only on hard disk"
	    else
		installdrive="$flashdrive $harddrive"
	    fi
	else
	# must be pccard/LS120
	    dd if=/dev/$flashdrive of=/dev/null count=10 > /dev/null 2>&1
	    if [ $? != 0 ] ; then
		installdrive="$harddrive"
		warn "Compact-flash missing, installing only on hard disk"
	    fi
	    if [ "$installdrive" = "" ] ; then
		dd if=/dev/$harddrive of=/dev/null count=10 > /dev/null 2>&1
		if [ $? != 0 ] ; then
		    harddrive_present="No"
		    installdrive="$flashdrive"
		    warn "Hard disk missing, installing only on compact-flash"
		fi
	    fi
	    if [ "$installdrive" = "" ] ; then
		installdrive="$flashdrive $harddrive"
	    fi
	fi
    else
	#
	# non-media install, read preinstall data from harddrive
	#
	mount_partition "$harddrive" f /mnt fatal
	if [ -f /mnt/${preinstalldir}/${install_config} ] ; then
	    . /mnt/${preinstalldir}/${install_config}
	else
	    error "discover_install_drive: ${preinstalldir}/$install_config not found"
	fi
	umount_partition /mnt
    fi

    if [ "$installdrive" = "" ] ; then
	error "discover_install_drive: Could not find a disk to do an install"
    fi

    inform "Disk to install is $installdrive"
}


#
# verify_package <mountpoint>
#
# Verify that the preinstall phase has put all the packages in the
# correct place and the install.config file is good.
#
verify_package() {

    local dir="$1"

    #
    # error checking
    #
    if [ ! -d "$dir" ] ; then
	error "verify_package: $dir not found"
    fi

    #
    # verify that we have an os package
    #
    if [ "$ospackage" = "" -o ! -f "$dir/$ospackage" ] ; then
	error "verify_package: ospackage $dir/$ospackage not found"
    fi

    #
    # set the upgrade flag
    #
    isupgrade=`echo $ospackage | grep jboot`

    # it is OK to not have a config package. 

    #
    # verify that the packlist is sane
    #
    if [ "$packlist" = "" ] ; then
	error "verify_package: packing list is empty"
    fi

    local pkg
    for pkg in $packlist ; do 
	if [ ! -f $dir/$pkg ] ; then
	    error "verify_package: $dir/$pkg not found"
	fi
    done

    #
    # Check to see if the packlist contains a jggsn package
    # If so, note this fact, as we'll resize the root filesystem
    # accordingly later
    #
    ggsn_pkg=`echo ${dir}/*ggsn*`
    if [ -f "$ggsn_pkg" ] ; then
	    ggsn_install="yes"
	    inform "GGSN installation"
	fi

    inform "Setting ospackage=$ospackage, configpackage=$configpackage"
    inform "Setting packlist=$packlist"
    inform "Setting isupgrade=$isupgrade"
}


#
# storage_check <source> <destination>
#
# Checks that there is enough storage to copy the files from the
# source to the destination 
#
storage_check() {

    local dir="$1"
    local destdir="$2"

    # verify that there is enough space 
    #
    local filelist=""
    [ ! -z "$configpackage" ] && filelist="$filelist ${dir}/${configpackage}"
    filelist="$filelist ${dir}/${ospackage}"
    for pkg in $packlist ; do
	filelist="$filelist ${dir}/$pkg"
    done
	
    suggested=0
    for file in $filelist ; do
	size=`du -sk $file | awk '{ sum = sum + $1 + 4 } END { print int(sum) }'`
	suggested=`expr ${suggested} + ${size}`
    done
    available=`df -k $destdir | awk '$1 != "Filesystem"  {print $4}'`

    if [ $suggested -ge $available ] ; then
	warn "The $destdir filesystem is low on free space."
	warn "This package requires ${suggested}k free, but there"
	warn "is only ${available}k available."
	warn_abort
    fi
}



#
# mount_os_bundle
#
# This is called in a PC card install to mount the install bits into
# the given mountpoint.    
#
mount_os_bundle() {
    
    if [ "$packagefsdev" = "" ] ; then
	error "mount_os_bundle: called with null packagefsdev"
    fi

    #
    # first mount the pc card on a mount point
    #
    mount -t cd9660 -r $packagefsdev $packagemnt
    if [ $? != 0 ] ; then
	error "mount_os_bundle: mount $packagefsdev failed"
    fi

    #
    # read the list of releases. Currently takes the first release in the
    # list without asking questions.
    #
    local releaselist
    local version
    if [ ! -f "$packagemnt/releaselist" ] ; then
	version=5.0
    else
	releaselist=`cat $packagemnt/releaselist`
    fi
    for version in $releaselist ; do
	break
    done

    #
    # set the installdir variable to the tree rooted under the release
    #
    installdir="$packagemnt/$version"

    #
    # source the contents of the install config file under the mountpoint
    #
    if [ ! -f "$installdir/$install_config" ] ; then
	error "mount_os_bundle: $installdir/$install_config not found"
    fi
    . $installdir/$install_config

    #
    # verify that the media package is sane and initialize some variables
    #
    verify_package $installdir
    if [ $? != 0 ] ; then
	error "mount_os_bundle: verify_package $installdir failed"
    fi

    inform "Packages mounted from the install media"

}


#
# copy_os_bundle
#
# This routine is called when a preinstall stage of a bootstrap
# install has placed package bits in the /var/tmp directory. It
# copies the jinstall package bits from the /var/tmp directory to
# the copy-destination. It also does a storage check to see that there is
# enough space in copy-destination
#
copy_os_bundle() {

    # mount the var drive
    mount_partition $harddrive f /mnt fatal
    if [ ! -d "/mnt/${preinstalldir}" ] ; then
	error "copy_os_bundle: could not find $preinstalldir in /var"
    fi

    #
    # verify that the preinstall package is sane
    #
    verify_package /mnt/${preinstalldir}
    if [ $? != 0 ] ; then
	error "copy_os_bundle: verify package /mnt/${preinstalldir} failed"
    fi

    #
    # check that there is enough storage space in /tmp to accomodate the
    # packages
    #
    storage_check /mnt/${preinstalldir} ${installdir}
    if [ $? != 0 ] ; then
	error "copy_os_bundle: storage check on ${installdir} failed"
    fi
    
    # if there is a jos-pre50, then untar it while copying. If it is a 
    # jboot, then copy it straight away
    #
    if [ "$isupgrade" != "" ] ; then
	pkgdir=`dirname $ospackage`
	$debug mkdir -p $installdir/$pkgdir
	$debug cp /mnt/${preinstalldir}/${ospackage} ${installdir}/$pkgdir
	if [ $? != 0 ] ; then
	    error "copy_os_bundle: error copying $ospackage to $installdir/$pkgdir"
        fi
    else 
	$debug tar xfz "/mnt/${preinstalldir}/${ospackage}" -C ${installdir}
	if [ $? != 0 ] ; then
	    error "copy_os_bundle: tar /mnt/${preinstalldir}/${ospackage} failed"
	fi
    fi
    
    # Copy the packages from the preinstalldir location to the
    # installdir location. This is because the preinstalldir may be on 
    # the same drive being installed
    #
    local pkgdir
    for pkg in $packlist ; do 
	pkgdir=`dirname $pkg`
	$debug mkdir -p $installdir/$pkgdir
	$debug cp /mnt/${preinstalldir}/$pkg ${installdir}/$pkgdir
	if [ $? != 0 ] ; then
	    error "copy_os_bundle: error copying $pkg to $installdir/$pkgdir"
	fi
    done

    # Copy the saved configurations
    #
    if [ -f "/mnt/${preinstalldir}/${configpackage}" ] ; then
	pkgdir=`dirname $configpackage`
	$debug mkdir -p $installdir/$pkgdir
	$debug cp /mnt/${preinstalldir}/${configpackage} ${installdir}/$pkgdir
	if [ $? != 0 ] ; then
	    error "copy_os_bundle: error copying $configpackage to ${installdir}/$pkgdir"
	fi
    fi

    #
    # unmount the var partition, else the next step which is partdrive 
    # will fail 
    #
    umount_partition /mnt

    inform "Packages and configurations copied to /tmp"
}



# ftp_os_bundle
#
# Ftp the os bundle from the ftp site and put it in our install
# directories
#
ftp_os_bundle() {

    local pkg="jinstall.tgz"

    #
    # configure the network 
    #
    notice "We need to set up the network to download the jinstall package"
    notice "Please answer the following questions:"
    notice
    init-network fxp0 /tmp/net-vars
    if [ $? != 0 ] ; then
	error "ftp_os_bundle: unable to setup the network"
    fi

    #
    # mount the var partition so that we have some space
    #
    local varfilesystem="/dev/${harddrive}${dsuffix}f"
    mount_filesystem "$varfilesystem" /mnt fatal
    if [ ! -d /mnt/tmp ] ; then
	error "ftp_os_bundle: expected tmp directory in var partition"
    fi

    #
    # get the URL of the os bundle. Try multiple times till fetch
    # succeeds
    #
    mkdir -p $installdir
    if [ $? != 0 ] ; then
	error "ftp_os_bundle: unable to create $installdir"
    fi
    while : 
    do
	getstring "URL for the jinstall package" ftpurl
	fetch -o "/mnt/tmp/$pkg" $ftpurl
	if [ $? != 0 ] ; then
	    warn "fetch $ftpurl failed."
	else
	    break
	fi
    done

    #
    # pkg_add the os bundle into the install directory in /tmp. The
    # files should be laid out exactly as the rest of the script expects
    # it.
    #
    export PKG_TMPDIR="/mnt/tmp"
    export PKG_FORCE="-f"
    export PKG_BOOTSTRAP="1"
    $debug pkg_add -p $installdir -f "/mnt/tmp/$pkg"

    #
    # unmount the var partition
    #
    umount_filesystem /mnt

    #
    # source the contents of the install config file under the
    # mountpoint. When sources the config, protect the installdrive from 
    # getting clobbered since we have already set it to be the flash and 
    # hard drive in discover_install_drive. Also configpackage is nuked.
    #
    if [ ! -f "$installdir/$install_config" ] ; then
	error "ftp_os_bundle: $installdir/$install_config not found"
    fi
    local installdrive
    . $installdir/$install_config
    configpackage=""

    #
    # verify the package
    #
    verify_package $installdir
    if [ $? != 0 ] ; then
	error "ftp_os_bundle: verify package ${installdir} failed"
    fi

    #
    # if there is a jos-pre50, then untar it.
    #
    if [ -z "$isupgrade" ] ; then
	$debug tar xfz "${installdir}/${ospackage}" -C ${installdir}
	if [ $? != 0 ] ; then
	    error "ftp_os_bundle: tar ${installdir}/${ospackage} failed"
	fi
    fi
    
    inform "Packages downloaded from $ftpurl to /tmp"
}


#
# makepart <partition> <size> <type>
#
# Create a disktab partition entry for the partition letter in $1,
# sized $2 blocks, with filesystem type $3.  $offset is adjusted to
# point to the start of the next partition.
#
# uses the offset variable implicitly
#
makepart() {
    if [ "$1" = "c" ]  ;then
	myoff=0;
    else
	myoff=$offset
    fi

    case "$3" in
	unused)
	    rest=" 0 0" ;;
	swap)
	    rest="" ;;
	*)
	    rest=" 0 0 0" ;;
    esac

    echo "${1}: $2 $myoff ${3}$rest"
    if [ "$1" != "c" ] ; then
	offset="`expr $offset + $2`";
    fi
}


#
# partdrive <disk>
#
# The hariest part of the code.  Partition the drive in $1, run newfs on all
# the new partitions. $1 is the drive to partition
# 
partdrive() {
    disk="$1";
    local configsize="" varsize="" disksize="" swapsize="" rootsize="" 
    local oconfigsize="" ovarsize="" odisksize="" oswapsize="" orootsize="" 
    local ol nl
    ol=/tmp/oldlabeltmp$$
    nl=/tmp/newlabeltmp$$

    echo "Partitioning $disk..."

    #
    # paranoia, unmount all slices on this disk. Else you may have problems
    # later on such as DIOSCSINFO errors.
    #
    umount "/dev/${disk}${dsuffix}*" > /dev/null 2>&1

    #
    # If this is not a media install, attempt to read the current disklabel
    # to figure out the partition sizes.  This is needed to preserve /var if
    # all that has happened is a repartition where space was moved from
    # /config to / (/var remains in the same place and the same size)
    # 
    if [ -z "$media_install" ] ; then
	ol=/tmp/curlabeltmp$$
	disklabel -r "$disk" > $ol
	if [ $? = 0 ] ; then
	    eval `awk ' / a:/ { print "orootsize="$2 }
			/ b:/ { print "oswapsize="$2 }
			/ c:/ { print "odisksize="$2 }
			/ e:/ { print "oconfigsize="$2 }
			/ f:/ { print "ovarsize="$2 } '   < $ol`
	else
	    #
	    # couldn't read disk label 
	    #
	    inform "Could not read disk label from $disk, creating new label."
	fi
    fi

    #
    # Destroy the existing disklabel, 'cause it may be crap and this can
    # confuse poor disklabel(1).
    #
    $debug dd if=/dev/zero of=/dev/$disk bs=512 count=10
    if [ $? != 0 ] ; then
	error "partdrive: dd zero bits into $disk failed"
    fi

    #
    # Write a clean disklabel.
    #
    $debug disklabel -w -r "$disk" auto
    if [ $? != 0 ] ; then
	error "partdrive: could not write a clean disklabel on $disk"
    fi

    #
    # Now read the disklabel back to get the size of the disk.
    #
    disklabel -r "$disk" > $ol
    if [ $? != 0 ] ; then
	error "partdrive: could not read the disklabel from $disk"
    fi

    #
    # Rip off everything up to and including the "N partitions" line and
    # store it in $nl--which is where our new partition table will appear.
    #
    sed '/^[0-9][0-9]* partitions/q;' < $ol > $nl

    #
    # Figure out the size of the disk.
    #
    disksize=`sed -n '/^sectors.unit:/ { s%sectors/unit: %%; p; q; }' < $ol`
    if [ "$disksize" = "" ] ; then
	error "unable to determine size of $disk"
    fi

    #
    # We used to only do this for pre-5.0 systems but we're lame now.
    #
    {
	echo "p 1 165 1 $disksize"
	echo "a 1"
    } | $debug fdisk -i -f - $disk
    if [ $? != 0 ] ; then
	error "partdrive: fdisk on $disk failed"
    fi

    disksize="`fdisk $disk | grep 'start.*size' | sed 's/.*size //;s/ .*$//;'`"
    sed "s%^sectors/unit:.*$%sectors/unit: $disksize%" ${nl} > ${nl}2
    nl=${nl}2

    #
    # If the disk is less than 1 gigabyte, its a flash drive...
    # otherwise it is probably a hard drive, attempt to read the
    # flash drive's label to determine the size to make the root
    # and config partitions on the hard drive
    #
    if [ $disksize -lt 2097152 ] ; then
	flash_drive_size=$disksize
    else
	flash_drive_read_label
    fi

    #
    # Calculate an "optimal allocation" for root file system space,
    # the rules...
    #    flash drives < 80M in size:
    #	    root gets 65M, config gets rest
    #    flash drives > 80M and < 120 M
    #       config gets 12M, root gets rest
    #    flash drives > 120M
    #       config gets 10%, root gets rest
    #
    # The hard drive's partitions are sized based on the flash drive's
    # sizes.  If a flash drive doesn't exit, default values are used
    # that simulate a 122 Meg flash drive.
    #
    if [ -n "$flash_drive_size" ] ; then
	if [ $flash_drive_size -ge 160000 ] ; then
	    if [ $flash_drive_size -gt 240000 ] ; then
		configsize=`expr $flash_drive_size / 10`
		rootsize=`expr $flash_drive_size - $configsize`
	    else
		configsize=$default_60_configsize
		rootsize=`expr $flash_drive_size - $configsize`
	    fi
	else
	    rootsize=$default_50_rootsize
	    configsize=`expr $flash_drive_size - $rootsize`
	fi
    else
	#
        # No flashdrive, then use defaults as if the standard
        # "122 M" flashdrive is installed.
	#
        # If flash_drive_default_size is not set, a default size
        # of 122M is used.   Currently it is set by the kontron
        # startup file to 245M for C&H and not otherwise.
        #
        if [ -z "$flash_drive_default_size" ] ; then
            rootsize=$rootsize_122
            configsize=$configsize_122
        else
            configsize=`expr $flash_drive_default_size / 10`
            rootsize=`expr $flash_drive_default_size - $configsize`
        fi
    fi

    #
    # Hard drive?
    #
    if [ "${harddrive#[wa]}" = "${disk#[wa]}" ] ; then
	# The swap slice (partition) size is determined as follows:
	# - if disk_size < 3GB
	#	swap_size = disk_size/4
	# - if disk_size >= 3Gb
	#	if memory_size < 1GB => swap_size = memory_size X 2
	#	if memory_size > 1GB => swap_size = 2GB - 2 pages
	# NOTE: The computation below is performed in blocks of 512B.
	if [ $disksize -lt 6291456 ] ; then
	    swapsize=`expr $disksize / 4`
	else
	    if [ $memsize -lt 2097152 ] ; then
		swapsize=`expr $memsize '*' 2`
	    else
		swapsize=`expr 4194304 - 16`
	    fi
	fi

	#
	# size of /var is all that remains
	#
	varsize=`expr $disksize - $swapsize - $configsize - $rootsize`
    else
	#
	# This is a flash drive.
	# (Note root and /config on the hard drive should be identical
	# in size to the ones on the flash).  Sizes are calculated above.
	#
    fi

    #
    # Now generate the partition table.
    #
    tmppart=/tmp/parttmp$$
    offset=0
    local newfspartlist
    {
	#
	# root partition
	#
	makepart a "$rootsize" 4.2BSD
	newfspartlist="a";

	#
	# Swap area.
	#
	if [ "$swapsize" != "" ] ; then
		makepart b "$swapsize" swap
	fi

	#
	# Make a "c" partition that's the whole disk.
	#
	makepart c "$disksize" unused

	#
	# config partition
	#
	makepart e "$configsize" 4.2BSD
	newfspartlist="$newfspartlist e";

	#
	# var partition
	#
	if [ "$varsize" != "" ] ; then
	    makepart f "$varsize" 4.2BSD
	    #
	    # if this is a media install, we will newfs /var
	    # if this is *not* a media install and the /var partition
	    # hasn't changed size, leave it alone to preserve its contents
	    #
	    if [ -n "$media_install" ] ; then
		newfspartlist="$newfspartlist f";
	    elif [ -z "$ovarsize" -o "$ovarsize" != "$varsize" ] ; then
		newfspartlist="$newfspartlist f";
	    fi
	fi
    } > $tmppart

    #
    # Append our new partition info.
    #
    { echo "#" ; cat $tmppart ; } >> $nl
    trace "*** the label look like this:"
    trace `cat $nl`
    trace "****"

    #
    # Write the new partition info and the boot blocks, and make the
    # filesystems.
    #
    inform "Installing disk label on $disk"
    $debug disklabel -B -R -r "$disk" $nl
    if [ $? != 0 ] ; then
	error "partdrive: install of final disklabel on $disk failed"
    fi

    for x in $newfspartlist ; do
	inform "Running newfs on ${1}${dsuffix}$x..."
	$debug newfs /dev/${1}${dsuffix}${x}
	if [ $? != 0 ] ; then
	    error "partdrive: newfs on /dev/${1}${dsuffix}${x} failed"
	fi
    done
}

#
# preserve_partdrive <disk>
#
# This routine is best called for a hard disk where you would like to
# preserve the var partition. It will check that the required
# partitions are there. If so, it will only newfs 'a' and 'e'
# partitions, and write a disklabel. The var partition ('f') is left 
# as is.
#
# This routine does not fail if there is an error. It returns a non-zero 
# value and the caller must call the destructive partdrive. 
#
preserve_partdrive() {
    disk="$1";
    local configsize="" varsize="" disksize="" swapsize="" rootsize="" 
    local ol

    echo "Cleaning up $disk..."

    #
    # paranoia, unmount all slices on this disk. Else you may have problems
    # later on such as DIOSCSINFO errors.
    #
    umount "/dev/${disk}${dsuffix}*" > /dev/null 2>&1

    #
    # read the disklabel and figure out the size of various partitions.
    # 
    ol=/tmp/curlabeltmp$$
    disklabel -r "$disk" > $ol
    if [ $? != 0 ] ; then
	warn "Unable to read disklabel of $disk. Hence need to partition it"
	return 1
    fi
    
    eval `awk '/ a:/ { print "rootsize="$2 }
	       / b:/ { print "swapsize="$2 }
	       / c:/ { print "disksize="$2 }
	       / e:/ { print "configsize="$2 }
	       / f:/ { print "varsize="$2 }    ' < $ol`

    #
    # If disk is greater than 1 gigabyte in size, then it is
    # a hard drive; if it has old partitioning on it we need
    # to clean it up to 6.X style, return and let partdrive
    # make 122M sytle partition.
    #
    if [ -n "$disksize" -a $disksize -gt 2097152 ] ; then
	if [ $rootsize -ne $rootsize_122 -o $configsize -ne $configsize_122 ] ; then
	    warn "Not 6.X style partitioning, need to repartition disk"
	    return 1
	fi
    fi

    #
    # check that the disk meets certain conditions
    #
    if [ "$rootsize" -lt $min_rootsize ] ; then
	warn "Root partition of $disk is $rootsize, expected $min_rootsize"
	warn "Need to partition $disk"
	return 1
    fi
    if [ -z "$swapsize" ] ; then
	warn "Swap partition of $disk is 0"
	warn "Need to partition $disk"
	return 1
    fi
    local swapneeded
    if [ $disksize -lt 6291456 ] ; then
	swapneeded=`expr $disksize / 4`
    else
	if [ $memsize -lt 2097152 ] ; then
	    swapneeded=`expr $memsize '*' 2`
	else
	    swapneeded=`expr 4194304 - 16`
	fi
    fi
    if [ "$swapsize" -lt "$swapneeded" ] ; then
	warn "Swap partition of $disk is too small"
	warn "Need to partition $disk"
	return 1
    fi

    if [ "$configsize" -lt $min_configsize ] ; then
	warn "Config partition of $disk is $configsize, expected $min_configsize"
	warn "Need to partition $disk"
	return 1
    fi
    if [ -z "$varsize" ] ; then
	warn "Var partition of $disk is 0"
	warn "Need to partition $disk"
	return 1
    fi


    #
    # newfs the a and e partitions, install bootblock and label
    #
    local newfspartlist="a e"
    for x in $newfspartlist ; do
	inform "Running newfs on ${1}${dsuffix}$x..."
	$debug newfs /dev/${1}${dsuffix}${x}
	if [ $? != 0 ] ; then
	    warn "preserve_partdrive: newfs on /dev/${1}${dsuffix}${x} failed"
	    return 1
	fi
    done

    inform "Installing disk label on $disk"
    $debug disklabel -B "$disk"
    if [ $? != 0 ] ; then
	warn "preserve_partdrive: install of final disklabel on $disk failed"
	return 1
    fi

    return 0;
}


#
# make_fstab <disk> <fstab-filename>
#
# Generate an /etc/fstab appropriate for a 5.x machine.
#
make_fstab() {

    # do some input error checking
    if [ "$1" = "" -o "$2" = "" ] ; then
	error "make_fstab: called with null disk parameter"
    fi

    local disk="${1}${dsuffix}"
    local hdrv="${harddrive}${dsuffix}"
    local flsh="${flashdrive}${dsuffix}"
    local fstabtmp="$2"

    #
    # for upgrades, use ad device in the fstab. For downgrades use wd device
    # in the fstab
    #
    local prefix
    if [ -z "$isupgrade" ] ; then
	prefix="w"
    else
	prefix="a"
    fi
    disk=${prefix}${disk#[wa]}
    hdrv=${prefix}${hdrv#[wa]}
    flsh=${prefix}${flsh#[wa]}

    #
    # figure out the alternate disk. If we are the flash, the
    # alternate is the harddrive. If we are the harddrive, the
    # alternate is the flashdrive. Note the altdisk can be null if,
    # this model is an olive.
    #
    local adsk=""
    if [ "$model" != "olive" ] ; then
	if [ "$disk" = "$hdrv" ] ; then
	    adsk="${flsh}"
	elif [ "$disk" = "$flsh" ] ; then
	    adsk="${hdrv}"
	else
	    error "make_fstab: alternate disk not set in model $re_name"
        fi
    fi

    {
	echo "#version 3"
	echo "# Device       Mountpoint  FStype  Options  Dump  Pass#"
	echo "/dev/${disk}a    /           ufs     rw        1    1"
	echo "/dev/${disk}e    /config     ufs     rw        2    2"
	echo "proc           /proc       procfs  rw        0    0"
	echo "/dev/${hdrv}f    /var        ufs     rw,noauto 2    0"
	echo "/dev/${hdrv}b    none        swap    sw        0    0"
	echo "/dev/${hdrv}b    /tmp        mfs     rw,noauto 0    0"

	if [ "$adsk" != "" ] ; then
	echo "/dev/${adsk}a    /altroot    ufs     rw,noauto 2    0"
	echo "/dev/${adsk}e    /altconfig  ufs     rw,noauto 2    0"
	fi
    } > $fstabtmp

    trace "*** fstab look like this:"
    trace `cat $fstabtmp`
    trace "***"
}


#
# addpackage <package-path> <destination>
#
# Adds a package given by packagefile at the
# destination/subdirectory. The routine expects var to be mounted
# under destination (It previously used to work by using an MFS.) The
# routine copies the packge to a tmp directory under the
# destination, does a chroot to destination before running pkg_add.
#
addpackage() {

    local packagepath="$1"
    local destination="$2"
    local package="`basename $packagepath`"

    #
    # error checking
    #
    if [ ! -f "$packagepath" ] ; then
	error "addpackage: $packagepath not found"
    fi

    #
    # set some environment variables for pkg_add. Disable the sourcing
    # of the require scripts and storage checks since they are not
    # necessary and they cause spurious warnings that may cause undue
    # concern to the customer
    #
    PKG_TMPDIR=/var/tmp
    export PKG_TMPDIR
    PKG_FORCE="-f"
    export PKG_FORCE
    PKG_BOOTSTRAP="1"
    export PKG_BOOTSTRAP
    PKG_STORAGE_CHECK_DISABLED="1"
    export PKG_STORAGE_CHECK_DISABLED

    #
    # pkg add is done by doing a chroot. Hence we need to copy the
    # package to the chrooted environment. The old approach was to use 
    # an MFS, now we expect var to be mounted under the destination.
    # 
    mkdir -p $destination/var/tmp
    cp $packagepath "$destination/var/tmp"
    if [ $? != 0 ] ; then
	error "addpackage: could not copy $packagepath to $destination/var/tmp"
    fi

    #
    # do the pkg_add
    #
    inform "Adding ${package}..."
    ${debug} chroot $destination pkg_add -f -v /var/tmp/$package
    if [ $? != 0 ] ; then
	error "addpackage: error during pkg_add /var/tmp/$package"
    fi
}

#
# mount_and_copy <packagefile> <destination>
#
# Mount a file that is compressed file system and tar out
# its contents to destination.  This is how the 5.0 root file system initially
# gets built (by untarring the content of the jboot package)
#
mount_and_copy() {

    local packagefile="$1"
    local destination="$2"

    #
    # error checking
    #
    if [ ! -f "$packagefile" ] ; then
	error "mount_and_copy: $packagefile not found"
    fi

    $debug vnconfig -s compressed -c /dev/vn0 $packagefile
    if [ $? != 0 ] ; then
	error "mount_and_copy: vnconfig $packagefile on /dev/vn0 failed"
    fi

    $debug mount_cd9660 /dev/vn0 $instrootmnt
    if [ $? != 0 ] ; then
	error "mount_and_copy: mount_cd9660 for $packagefile failed"
    fi

    inform "Making root filesystem..."
    $debug tar cCf $instrootmnt - . | $debug tar --unlink -xpf - -C $destination
    if [ $? != 0 ] ; then
	error "mount_and_copy: failed doing the tar"
    fi

    $debug umount $instrootmnt
    if [ $? != 0 ] ; then
	error "mount_and_copy: unmount $instrootmnt for $packagefile failed"
    fi

    $debug vnconfig -u /dev/vn0
    if [ $? != 0 ] ; then
	error "mount_and_copy: vnconfig -u for $packagefile failed"
    fi
}



#
# empty_config <mountpoint>
#
# Create an empty configuration. Expects all filesystems mounted.
#
empty_config() {

    inform "Creating default configuration..."

    #
    # some error checking
    #
    if [ "$1" = "" ] ; then
	error "empty_config: need a mountpoint to restore the config"
    fi

    #
    # create an empty juniper.conf
    #
    [ ! -f /tmp/net-vars ] && mkempty /tmp/net-vars
    create-juniper-conf /tmp/net-vars /etc/default.conf $1/config/juniper.conf

}


#
# restore_config <mountpoint>
#
# This routine restores a saved config 
#
restore_config() {

    inform "Restoring backed up configurations..."

    #
    # some error checking
    #
    if [ "$1" = "" ] ; then
	error "restore_config: need a mountpoint to restore the config"
    fi
    if [ ! -f "$installdir/$configpackage" ] ; then
	error "restore_config: $installdir/$configpackage not found"
    fi

    if [ -d $1/var/etc ]; then
	#
	# We are restoring the critical files that we saved earlier.
	# Anything else in $1/etc is potentially bogus - remove it
	#
	rm -f $1/var/etc/*.conf
    fi
    $debug tar --unlink -xzf $installdir/$configpackage -C $1
    if [ $? != 0 ] ; then
	error "restore_config: failed to restore saved configs"
    fi
}


#
# extract_config <mountpoint>
#
# Extract a config from the DOS partition on the install media
#
extract_config() {
    local configfsdev
    local retstatus=1
    local config_file

    #
    # some error checking
    #
    if [ "$packagefsdev" = "" ] ; then
	return 1
    fi

    configfsdev=`echo ${packagefsdev} | sed -e 's/s2$/s1/'`

    if [ "$1" = "" ] ; then
	error "extract_config: need a mountpoint to extract the config"
    fi

    [ ! -d /tmp/configdir ] && mkdir /tmp/configdir

    mount -t msdos ${configfsdev} /tmp/configdir || return 1

    for config_file in juniper.conf.gz juniper.conf
    do
	if [ -s /tmp/configdir/${config_file} ]
	then
	    cp /tmp/configdir/${config_file} $1/config
	    inform "Extracted ${config_file} from ${configfsdev}"
	    retstatus=0
	    break
	fi
    done

    umount /tmp/configdir

    return ${retstatus}
}


# do_snapshot <mountpoint>
# 
# Create a snapshot of the currently installed packages. This acts as a
# reference for rollback command. 
#
do_snapshot() {
    local mnt="$1"
    local pkg_sw_dir="$mnt/var/sw/pkg"
    local etc_db_dir="$mnt/etc/db/pkg"

    #
    # first truncate the rollback file.
    #
    $debug > $pkg_sw_dir/rollback

    #
    # copy the packages to /var/sw/pkg
    #
    local pkg
    for pkg in $packlist ; do 
	local pkgname=`echo $pkg | sed -e s,-domestic,, -e s,-export,,`
	$debug cp $installdir/$pkg  $pkg_sw_dir/$pkgname
	if [ $? != 0 ] ; then
	    warn "Unable to save $pkg for rollback"
	    return 1
	fi
    done

    #
    # generate the rollback file
    #
    grep . $etc_db_dir/*/+COMMENT | \
    sed -e 's,'${etc_db_dir}'/\([^/]*\)/+COMMENT:,\1=,' -e 's,=.*\[\(.*\)\].*, \1,' > $pkg_sw_dir/rollback
    if [ $? != 0 ] ; then
	warn "Creating file /var/sw/pkg/rollback had errors"
    fi

    return 0
}


# make_symlink <src> <target>
#
# if <target> does not already point at <src>
# make the link.
# The goal is to minimize writes to the flash

make_symlink() {
    local src target target_dir
    src=$1 
    target=$2

    if [ -h $DESTDIR$target ]; then
	case `/bin/ls -l $DESTDIR$target` in
	*"> $src")
	    trace "make_symlink: ok: $DESTDIR$target -> $src"
	    return;;
	esac
    fi
    trace "make_symlink: making: $DESTDIR$target -> $src"
    target_dir=`dirname $DESTDIR$target`
    [ -d $target_dir ] || mkdir -p $target_dir
    ${LN:-/bin/ln} -sf $src $DESTDIR$target
}

# make_symlinks <package-name>
#
# If the file symlinks exists, we compare it to
# the one for the previous version of <package-name>
# and implement any changes.

make_symlinks() {
    local symlinks old_symlinks

    symlinks=${1:-./$package.symlinks}
    old_symlinks=${2:-$pkgdir/$package.symlinks}

    if [ -s $symlinks ]; then
	if [ -s $old_symlinks ]; then
	    # get rid of links which may no longer be correct
	    diff $old_symlinks $symlinks | while read op src target flags
	    do
		case "$op" in
		"<") # delete - but only if it still points at src
		     # and isn't no_unlink
		     case "$flags" in
		     *no_unlink*) continue;;
		     esac
		     if [ -h $DESTDIR$target ]; then
			 case `/bin/ls -l $DESTDIR$target` in
			 *"> $src")
			     trace "make_symlinks: removing: $DESTDIR$target -> $src"
			     /bin/rm -f $DESTDIR$target
			     ;;
			 esac
		     fi
		     ;;
		esac
	    done
	fi
	# make sure that the ones that should be there, are.
	while read src target flags
	do
	    make_symlink $src $target
	done < $symlinks
    fi
}

mount_isofs() {
    local package=$1
    local pkgpath=$2
    local mntpoint=$3
    local u=0
    local vnd

    trace "mount_isofs: $*"
    
    [ -d $mntpoint ] || mkdir -p $mntpoint

    while [ $u -lt 42 ]
    do
	vnd=vn$u
	if vnconfig -q -c -s compressed $vnd $pkgpath autoffset; then
	    if mount -t cd9660 -r /dev/$vnd $mntpoint; then
		inform "Mounted $package on $mntpoint (/dev/$vnd)"
	    else
		error cannot mount $pkgpath
	    fi
	    return
	fi
	u=`expr $u + 1`
    done
    error cannot vnconfig $pkgpath
}

umount_isofs() {
    local package=$1
    local mntpoint=$2
    local vnd junk rest
    
    trace "umount_isofs: $*"

    mount | grep " ${mntpoint:-$DESTDIR/packages.*$package}" |
    while read vnd junk mntpoint rest
    do
	if umount $mntpoint; then
	    inform Unmounted $mntpoint
	    vnconfig -u $vnd
	else
	    warn cannot unmount $mntpoint
	fi
    done
}

# a fixed location makes everything simpler
jbase_mnt=/packages/mnt/jbase

#
# mount_jbase
#
# Extract jbase from jbundle and mount it, so that we can chroot
# pkg_add etc.
#
mount_jbase() {
    local jbundle=$1
    local mnt=$2
    local jbase=jbase-$osrelease

    inform "Adding jbase..."
    rm -rf $mnt/etc/db/pkg/jbase
    mkdir -p $mnt$jbase_mnt $mnt/tmp/jbase $mnt/etc/db/pkg/jbase \
	     $mnt/var/run
    case "$jbundle" in
    *-signed*)
	# we don't use -signed jbundles here, but just in case,
	# extract the real jbundle from the -signed.tgz
	tar zxf $jbundle -C /tmp
	jbundle=`echo /$jbundle | sed 's,^.*/\(jbund.*\)-signed\(.tgz\),/tmp/\1\2,'`
	# XXX skip verifying the hash?
	# verify_pkg $jbundle.md5
	;;
    esac
    # grab the jbase package out of the jbundle
    tar zxf $jbundle -C /tmp 'jbase*'
    # unpack it somewhere on the target fs
    tar zxf /tmp/$jbase.tgz -C $mnt/tmp/jbase
    if [ -s $mnt/tmp/jbase/packages/$jbase ]; then
	rm -f /tmp/$jbase.*
	# move the bits we want to where they belong
	mv $mnt/tmp/jbase/jbase* $mnt/tmp/jbase/packages/$jbase $mnt/packages
	# lose the bits we don't need
	rm -f $mnt/tmp/jbase/+INSTALL
	# and "register" the package as installed
	mv $mnt/tmp/jbase/* $mnt/etc/db/pkg/jbase
	# keep it neat
	rm -rf $mnt/tmp/jbase
	# jbundle's +INSTALL will want to see /var/run/jbase.require
	grep '^jbase_.*=' $mnt/etc/db/pkg/jbase/+REQUIRE |
	    sed 's/^/current_/' > $mnt/var/run/jbase.require
	ln -sf $jbase $mnt/packages/jbase
	# Prepare for downgrade.
	# These are the top level dirs in jbase and
	# provided *bin and usr are covered we are ok,
	# so adding new things to jbase need not impact us here.
	local d
	for d in bin etc packages sbin usr
	do
	    ln -sf ../jbase_mnt/$d $mnt$jbase_mnt/$d
	done
	# now we need to actually mount it
	mount_isofs jbase $mnt/packages/$jbase $mnt$jbase_mnt
	( DESTDIR=$mnt make_symlinks $mnt/packages/jbase.symlinks )
	# Test for the presense of a pathname that isn't likely to
	# change as a final check that all went well
	if [ -s $mnt/packages/mnt/jbase/usr/lib/pam_unix.so ]; then
	    # ensure there is a copy of init for downgrading
	    # its all rather ugly, but unavoidable
	    # XXX remove this when 5.3 is extinct
	    cp -p $mnt/packages/mnt/jbase/sbin/init $mnt/sbin/init.bak
	    return 0
	fi
    fi
    error "cannot mount $jbase on $mnt$jbase_mnt"
}

umount_jbase() {
    local mnt=$1
    
    umount_isofs jbase $mnt$jbase_mnt
}
    
# 50_preinstall_fixups <mountpoint>
#
# This is the marshpit for all the misc things that need to happen in
# a 5.0 install that do not have do with laying the packages. As and 
# when you think of stuff, put them here.
#
50_preinstall_fixups() {
    
    local mnt="$1"
    local disk="$2"
    if [ "$mnt" = "" ] ; then
	error "50_preinstall_fixups: requires a mountpoint for the root filesystem"
    fi
    if [ "$disk" = "" ] ; then
	error "50_preinstall_fixups: requires the name of the install disk"
    fi

    #
    # Create the new fstab.
    #
    local fstabtmp="/tmp/fstab$$"
    make_fstab $disk $fstabtmp
    $debug cp $fstabtmp $mnt/etc/fstab
    $debug chmod 444 $mnt/etc/fstab

    #
    # create the password databases
    #
    chroot /mnt pwd_mkdb -p -d /etc /etc/master.passwd 
    if [ $? != 0 ] ;  then
	warn "Could not create password databases"
    fi

    return
}


#
# 50_postistall_fixups <mountpoint> <installdrive>
# 
# Do the post-install fixups. Again this contains miscellaneous things 
# that need to be scheduled after the install has happened.
#
50_postinstall_fixups() {
    
    local mnt="$1"
    local disk="$2"
    if [ "$mnt" = "" ] ; then
	error "50_postinstall_fixups: requires a mountpoint for the root filesystem"
    fi
    if [ "$disk" = "" ] ; then
	error "50_postinstall_fixups: requires the name of the install disk"
    fi
	
    #
    # move the ssh files to the new location needed by 5.0 OpenSSH. If
    # no keys are present, rc scripts will generate them.  
    #
    if [ -f $mnt/etc/ssh_host_key ] ; then
	$debug mkdir -p $mnt/etc/ssh
	if [ $? = 0 ] ; then
	    $debug mv $mnt/etc/ssh_* $mnt/etc/ssh
	else
	    warn "Could not create /etc/ssh directory"
        fi
    fi

    #
    # We copied some lines from the original /boot/loader.conf into
    # a temp config file. Now we copy it back into the loader.conf
    # file. This is only used by Hobson and pepsi simulation 
    #
    tmppersistconf="/tmp/presistconf$$"
    if [ -f $mnt/var/tmp/preinstall_boot_loader.conf ] ; then
	cat $mnt/var/tmp/preinstall_boot_loader.conf | \
	    grep -e 'ata' -e 'cid' -e 'retype' -e 'model' > $tmppersistconf
    fi
    if [ -w $mnt/boot/loader.conf ] ; then
	cat $tmppersistconf >> $mnt/boot/loader.conf
    fi

    if [ "$harddrive_present" = "Yes" ] ; then

	#
	# clean up utmp and wtmp since the size of entries are different
	# in 4.x and 5.0
	#
	$debug > $mnt/var/log/utmp
	$debug > $mnt/var/log/wtmp

	#
	# create a snapshot for rollback
	#
	do_snapshot $mnt

	#
	# remove the /var/tmp/preinstall directory if it is present. It
	# contains temporary files created by jinstall 
	#
	$debug rm -rf $mnt/var/$preinstalldir
    else
	warn "Hard disk missing, the rollback file was not created"
    fi

    return
}


#
# make_new_root <install-drive>
#
# Make a JUNOS 5.0 filesystem on drive $1, which is assumed to have been
# already newfs'ed. 
#
make_new_root() {

    local disk="$1"
    local installfilesystem="/dev/$1${dsuffix}a"
    local configfilesystem="/dev/$1${dsuffix}e"
    local varfilesystem="/dev/${harddrive}${dsuffix}f"

    #
    # mount the install filesystem
    #
    mount_filesystem "$installfilesystem" /mnt fatal
    
    #
    # mount the var filesystem
    #
    $debug mkdir -p /mnt/var
    $debug chmod 755 /mnt/var
    if [ "$harddrive_present" = "Yes" ] ; then
	mount_filesystem "$varfilesystem" /mnt/var fatal
    else
	setup_tmp $tmpvarsize /mnt/var
    fi

    #
    # mount the config filesytem.
    #
    $debug mkdir -p /mnt/config
    $debug chmod 755 /mnt/config
    mount_filesystem "$configfilesystem" /mnt/config fatal 

    #
    # install the OS package
    #
    mount_and_copy ${installdir}/$ospackage /mnt

    mount_jbase ${installdir}/$packlist /mnt
    
    #
    # do the misc housekeeping stuff
    #
    50_preinstall_fixups /mnt $disk

    #
    # install the jbundle. Right now there is no jbundle but
    # individual packages. So install them one at a time.
    #
    for pkg in $packlist ; do 
	addpackage ${installdir}/$pkg /mnt
    done

    #
    # Untar the configuration files and ssh keys. If this is a media
    # install, then create an empty configuration.
    #
    if [ ! -z "$configpackage" ] ; then
	restore_config /mnt
    elif [ ! -z "$media_install" ] ; then
	extract_config /mnt || empty_config /mnt
    fi

    #
    # do any other post install stuff that needs to happen
    #
    50_postinstall_fixups /mnt $disk

    umount_jbase /mnt
    umount_filesystem /mnt/config
    umount_filesystem /mnt/var
    umount_filesystem /mnt
}


#(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
# This is pre50 install code
#
# pre50_prepreinstall_fixups <mountpoint> <installdrive>
#
# We need to save some additional files before we start laying the
# root filesystem 
#
pre50_prepreinstall_fixups() {

    local mnt="$1"
    if [ "$mnt" = "" ] ; then
	error "pre50_prepreinstall_fixups: requires a mountpoint for the root filesystem"
    fi

    #
    # this file is overwritten when putting a 4.x root filesystem. So save it
    #
    cp $mnt/var/log/messages ${installdir}
}
 
#(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
# This is pre50 install code
#
# pre50_preinstall_fixups <mountpoint> <installdrive>
#
# This is a marshpit for all the misc things that sysinstall does and
# JUNOS pre50 systems expect. If there is something other than
# installing the OS package and Jbundle, you can expect to find it here.
#
# Various things have to be fixed, according to sysinstall such as
# running mtree and creating devices. Also create JUNOS specific
# directories. Mountpoint is the directory on which the 4x JUNOS has
# been installed
#
pre50_preinstall_fixups() {

    local mnt="$1"
    local disk="$2"
    if [ "$mnt" = "" ] ; then
	error "pre50_preinstall_fixups: requires a mountpoint for the root filesystem"
    fi
    if [ "$disk" = "" ] ; then
	error "pre50_preinstall_fixups: requires the name of the install disk"
    fi

    #
    # Create the new fstab.
    #
    local fstabtmp="/tmp/fstab$$"
    make_fstab $disk $fstabtmp
    $debug cp $fstabtmp $mnt/etc/fstab
    $debug chmod 444 $mnt/etc/fstab

    #
    # run mtree on the root, usr and dist directories
    #
    $debug chroot $mnt mtree -deU -f /etc/mtree/BSD.root.dist > /dev/null 2>&1
    if [ $? != 0 ] ; then
	error "pre50_preinstall_fixups: mtree BSD.root.dist failed"
    fi

    $debug chroot $mnt mtree -deU -f /etc/mtree/BSD.usr.dist -p /usr > /dev/null 2>&1
    if [ $? != 0 ] ; then
	error "pre50_preinstall_fixups: mtree BSD.usr.dist failed"
    fi

    $debug chroot $mnt mtree -deU -f /etc/mtree/BSD.var.dist -p /var > /dev/null 2>&1
    if [ $? != 0 ] ; then
	error "pre50_preinstall_fixups: mtree BSD.var.dist failed"
    fi


    #
    # makedev wd and wfd devices
    #
    for x in 0 1 2 4
    do
	$debug chroot $mnt sh -c "cd /dev; ./MAKEDEV wd${x}; ./MAKEDEV wd${x}${dsuffix}a;"
	if [ $? != 0 ] ; then
	    error "pre50_preinstall_fixups: MAKEDEV wd${x} failed"
        fi
    done
    $debug chroot $mnt sh -c 'cd /dev; ./MAKEDEV wfd0'
    if [ $? != 0 ] ; then
	error "pre50_preinstall_fixups: MAKEDEV wfd0 failed"
    fi

    #
    # create the package entries for the ospackage which is called junos.
    #
    $debug mkdir -p $mnt/etc/db/pkg/junos ;
    mkempty $mnt/etc/db/pkg/junos/+CONTENTS 
    local ostag
    [ "$osedition" = "export" ] || ostag="(Export restricted edition)"
    echo "JUNOS base [$osrelease] $ostag" > $mnt/etc/db/pkg/junos/+COMMENT 
    echo "JUNOS base [$osrelease] $ostag" > $mnt/etc/db/pkg/junos/+DESC

    #
    # create some misc directories
    #
    mkempty $mnt/boot.config
    $debug mkdir $mnt/altroot
    $debug chmod 755 $mnt/altroot
    $debug mkdir $mnt/altconfig
    $debug chmod 755 $mnt/altconfig

    return
}
    


#(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
# This is pre50 install code
#
# pre50_postinstall_fixups <mountpoint> <installdrive>
# 
# Do the post-install fixups for a pre50 install. Again this contains
# miscellaneous things that need to be scheduled after the install
# has happened. 
#
pre50_postinstall_fixups() {
    
    local mnt="$1"
    local disk="$2"
    if [ "$mnt" = "" ] ; then
	error "pre50_postinstall_fixups: requires a mountpoint for the root filesystem"
    fi
    if [ "$disk" = "" ] ; then
	error "pre50_postinstall_fixups: requires the name of the install disk"
    fi

    #
    # Fix the disklabel with the right bootloaders.
    #
    $debug disklabel -B -b $mnt/usr/mdec/boot1 -s $mnt/usr/mdec/boot2 $disk
    if [ $? != 0 ] ; then
	error "pre50_postinstall_fixups: install of bootloaders failed"
    fi

    #
    # move the ssh files to the location needed by  DearFellow SSH. If
    # no keys are present, generate them.  
    #
    if [ -f $mnt/etc/ssh/ssh_host_key ] ; then
	$debug mv $mnt/etc/ssh/ssh_host_key* $mnt/etc
	$debug rm -rf $mnt/etc/ssh
    fi
    if [ -x $mnt/usr/bin/ssh-keygen -a ! -f $mnt/etc/ssh_host_key ] ; then
	chroot $mnt ssh-keygen -b 1024 -N '' -f /etc/ssh_host_key
    fi

    #
    # generate db files based on master.passwd at present due to   
    # untar of configpackage.
    # create the password databases.
    #
    pwd_mkdb -p -d $mnt/var/etc $mnt/var/etc/master.passwd
    if [ $? != 0 ] ;  then
	warn "Could not create password databases"
    fi

    #
    # clean up utmp and wtmp since the size of entries are different
    # in 4.x and 5.0
    #
    $debug > $mnt/var/log/utmp
    $debug > $mnt/var/log/wtmp

    #
    # copy kernel.GENERIC as a backup kernel
    #
    if [ -f $mnt/kernel.GENERIC ] ; then
	mv $mnt/kernel.GENERIC $mnt/.kernel.jkernel.backup
    fi

    #
    # copy /var/log/messages from the temporary save location
    #
    if [ -f $installdir/messages ] ; then
	cp $installdir/messages $mnt/var/log/messages
    fi

    #
    # create a snapshot for rollback
    #
    do_snapshot $mnt

    #
    # remove the /var/tmp/preinstall directory if it is present. It
    # contains temporary files created by jinstall 
    #
    $debug rm -rf $mnt/var/$preinstalldir

    return
}


#(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
# This is pre50 install code
#
# make_new_root_pre50 <install-drive>
#
# Make a JUNOS 4.x filesystem on drive $1, which is assumed to have been
# already newfs'ed. 
#
make_new_root_pre50() {
    
    local disk="$1"
    local installfilesystem="/dev/$1${dsuffix}a"
    local configfilesystem="/dev/$1${dsuffix}e"
    local varfilesystem="/dev/${harddrive}${dsuffix}f"

    #
    # mount the install filesystem
    #
    mount_filesystem "$installfilesystem" /mnt fatal
    
    #
    # mount the var filesystem
    #
    $debug mkdir -p /mnt/var
    $debug chmod 755 /mnt/var
    mount_filesystem "$varfilesystem" /mnt/var fatal

    #
    # mount the config filesytem.
    #
    $debug mkdir -p /mnt/config
    $debug chmod 755 /mnt/config
    mount_filesystem "$configfilesystem" /mnt/config fatal 

    #
    # do some early housekeeping stuff
    #
    pre50_prepreinstall_fixups /mnt

    #
    # Now grab the binary files and lay it on the drive
    #
    inform "Making root filesystem..."
    $debug cat ${installdir}/bin/bin.?? | tar --unlink -xpzf - -C /mnt
    if [ $? != 0 ] ; then
	error "make_new_root_pre50: untar of ${installdir}/bin failed"
    fi
    cp $installdir/bin/bin.mtree /mnt/etc/mtree/bin.mtree
    if [ $? != 0 ] ; then
	error "make_new_root_pre50: error copying bin.mtree from $installdir"
    fi
    $debug chroot /mnt mtree -eU -f /etc/mtree/bin.mtree > /dev/null 2>&1
    if [ $? != 0 ] ; then
	error "make_new_root_pre50: mtree /etc/mtree/bin.mtree failed"
    fi

    #
    # Now grab the des files and lay it on the drive. libcrypt link is 
    # created by the des install, so remove it so that it can be made
    # correctly. 
    #
    if [ -d ${installdir}/des ]; then
	rm -f /mnt/usr/lib/libcrypt.so.2.0;
	$debug cat ${installdir}/des/des.?? | tar $topts --unlink -xpzf - -C /mnt
	if [ $? != 0 ] ; then
		error "make_new_root_pre50: untar of ${installdir}/des failed"
	fi
	cp $installdir/des/des.mtree /mnt/etc/mtree/des.mtree
	if [ $? != 0 ] ; then
		error "make_new_root_pre50: error copying des.mtree from $installdir"
	fi
	$debug chroot /mnt mtree -eU -f /etc/mtree/des.mtree > /dev/null 2>&1
	if [ $? != 0 ] ; then
		error "make_new_root_pre50: mtree /etc/mtree/des.mtree failed"
	fi
    fi
    #
    # Pre50 housekeeping things. This includes sysinstall "bogons",
    # from install.c and creating of misc JUNOS specific directories 
    # If there are more tweaks, put them in the housekeeping routine
    # rather than cluttering this place
    #
    pre50_preinstall_fixups /mnt $disk

    #
    # Install jbundle. Grep out a pesky syntax error due to a gratuitous
    # storage_check performed by jbundle's REQUIRE script.
    #
    for pkg in $packlist ; do 
	addpackage $installdir/$pkg /mnt 2>&1 | grep -v 'syntax error'
    done

    #
    # Untar the configuration files and ssh keys. If this is a media
    # install, then create an empty configuration.
    #
    if [ ! -z "$configpackage" ] ; then
	restore_config /mnt
    elif [ ! -z "$media_install" ] ; then
	empty_config /mnt
    fi

    #
    # Housekeeping things that need to happen after install
    #
    pre50_postinstall_fixups /mnt $disk

    umount_filesystem /mnt/config
    umount_filesystem /mnt/var
    umount_filesystem /mnt

}


#
# Now the main script.
#
main() {

    local ol disksize 

    #
    # initialize the environment, run pccardd
    #
    initialize

    # 
    # recognize what model you are running on
    #
    recognize_model

    #
    # preen filesystems so that they mount with less stress
    #
    preen_filesystems

    #
    # discover the drive on which install must happen. If this is a media
    # install, then it is both the flash and harddrive. Else it is the
    # drive that has been set by the preinstall stage.
    #
    discover_install_drive

    #
    # If there is no media then there was a preinstall. So copy the bits
    # from the preinstall location.
    #
    if [ -z "$media_install"  ] ; then
	copy_os_bundle

    elif [ "$media_install" = "pccard" ] ; then
	media_prompt_user
	mount_os_bundle

    elif [ "$media_install" = "floppy" ] ; then
	media_prompt_user

    else
	error "The installer is unable to detect install method"

    fi

    #
    # Now there is no turning back. Partition the drives
    #
    for disk in $installdrive ; do
	local disknum=${disk#[wa]}
	local hardnum=${harddrive#[wa]}

	#
	# If we are working on the harddrive and this not a media install,
	# see if we want to preserve the partitioning (to save /var contents)
	#
	if [ "$disknum" = "$hardnum" -a -z "$media_install" ] ; then
	    preserve_partdrive $disk
	    if [ $? != 0 ] ; then
		partdrive $disk
	    fi
	else
            #
	    # This is not a harddrive or
	    # we are doing a media install (always partition)
	    #
	    partdrive $disk
	fi
    done

    #
    # Setup the var filesystem so that it has some essential directories
    # needed by pkg_add and stuff
    #
    if [ "$harddrive_present" = "Yes" ] ; then
	setup_var
    fi

    #
    # if the install media is floppy, now fetch the jinstall package.
    #
    if [ "$media_install" = "floppy" ] ; then
	ftp_os_bundle
    fi

    #
    # Now lay the bits on the drives.
    #
    for disk in $installdrive ; do 
	inform "Installing JUNOS on $disk..."
	if [ -z "$isupgrade" ] ; then
	    make_new_root_pre50 $disk
	else
	    make_new_root $disk
	fi
    done

    #
    # Set the next boot device 
    #
    setup_nextbootdev

    #
    # save the log file. Do it from within this process, since the
    # harddrive variable is set here
    #
    if [ ! -z "$INSTALL_LOG" ] ; then
	save_install_log
    fi
}

case ./$0 in
*/install)
    # debugging...
    eval `echo $1 | sed 's,.*jbundle-\([^-]*\)-\([^-]*\)[\.-].*,osrelease=\1 osedition=\2,'`
    mount_jbase "$@"
    exit 0
    ;;
esac

#
# Setup /tmp. Also creates the location where the bits are kept.
#
setup_tmp $tmpsize /tmp /tmp/preinstall limit

#
# Run the main program with output redirection. 
#
if [ -z "$INSTALL_LOG" ] ; then
    main
else
    main 2>&1 | write_install_log
fi

#
# Reboot.
#
$debug /sbin/reboot
while : ; do 
done


