#!/bin/sh
#
# Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
#pragma ident	"@(#)install-setup.sh	1.9	06/06/16 SMI"
#
##############################################################################
# This is the main entry point into the Solaris Install scripts.
# The set of install scripts that get invoked when one boots the
# installation media are described below:
# 
# svc:/system/svc/restarter - The default smf(5) restarter that is responsible
#			      for starting the system/install-discovery and
#			      system/install-setup services.
# 
# /sbin/install-common - Common install routines, mainly for debugging.
#                        Sourced by most other install scripts.
# 
# /sbin/install-discovery - Does initial bootparams/DHCP discovery of
#                           networking and install-related parameters,
#                           parses install-related boot arguments,
#                           configures system devices, and finally exits.
#                           init then takes over, starts upping the runlevel,
#                           and when it gets to runlevel 2, invokes
#                           install-setup.
# 
# /sbin/install-setup - Implements install policy regarding memory
#                       requirements, windowing environment, locales, invokes
#                       sysid-setup to do initial system identification,
#                       and finally runs the windowing system if we are
#                       on a system capable of doing so.  Finally, we
#                       call install-ui-start to fire up the install UI.
# 
# /sbin/sysid-setup - Asks user for locale/language/terminal and on x86
#                     platforms, asks for keyboard/mouse/display
#                     configuration, so that the windowing system can be
#                     invoked properly.
# 
# /sbin/install-ui-start - This script invokes the base Install UI.
#                          There are two base UIs - X Windows and non-X
#                          Windows. In the X Windows case, we configure the
#                          X server using setup-window-config, and then
#                          start the X server.  Part of setup-window-config
#                          writes out a script to be executed by the X server,
#                          and that script invokes install-begin.  In the
#                          non-X Windows UI, we simply invoke
#                          install-begin directly, inline, on the
#                          console.
# 
# /sbin/setup-window-config - This script configures the windowing system
#                             to either run dtwm, or twm.  It turns off
#                             the screensaver, configures, menus,
#                             backgrounds, etc.
# 
# /sbin/install-begin - Begins actual installation.  This completes
#                       system identification by running the GUI sysid
#                       wizard, or the text-based sysid tools.  Once that
#                       is complete, install-solaris is run to run the
#                       install application.
# 
# /sbin/sysid-finish - This script completes system identification by
#                      running the GUI wizard, or a text-based sysid tool in a
#                      terminal.
# 
# /sbin/install-solaris - The actual install application.  This script
#                         was formerly known as suninstall and is responsible
#                         for processing a jumpstart install or
#                         interactive install.
# 
# /sbin/setup-launcher - This script is invoked at the end of
#                        install-solaris, to run the Solaris Install
#                        Launcher, or configure it to run after reboot,
#                        depending on the type of install being performed.
# 
# The graphical flow can be depicted like this:
# 
# /etc/inittab --> /sbin/install-discovery
#    |
#    v
# /sbin/install-setup
#    |
#    +---> /sbin/sysid-setup
#    |
#    v
# /sbin/install-ui-start
#    |
#    +--> X server (if applicable)
#    |         |
#  (no X)     (X)
#    |         |
#    |         |
#    v         v
# /sbin/install-begin
#    |
#    +--> /sbin/sysid-finish
#    |
#    v
# /sbin/install-solaris
#    |
#    +--> install application (ttinstall or GUI wizard)
#    |
#    +--> /sbin/setup-launcher
#    |
#    v
# /bin/sh or reboot
# 
##############################################################################

INSTALL_LOG=/tmp/install_log
INSTALL_CONSOLE=/tmp/install_console
SHELL=/sbin/sh
TEXTDOMAIN=SUNW_INSTALL_SCRIPTS
PATH=/sbin:/usr/sbin/install.d:${PATH}
YES=yes
NO=no

# make home dir to a writeable place
HOME=/tmp/root
export SHELL TEXTDOMAIN PATH HOME YES NO

# Local Variables
KDMCONFIG_NOGUI=/tmp/root/var/tmp/kdmconfig.nogui
OWCONFIG_FILE=/tmp/root/etc/openwin/server/etc/OWconfig
SWAPPART_FILE=/.swappart
SWAP2_FILE=/swap2

# where to store locale variables
LOCFILE=/tmp/.localeFile

NETBOOTINFO=/usr/lib/inet/wanboot/netbootinfo

# minimum memory to perform various install tasks

if [ `uname -p` = "sparc" ] ; then
	MIN_INSTALL_PHYSMEM=64
	MIN_JAVA_INSTALL_PHYSMEM=512

	# unpacking all of X into memory takes up around 150Mb
	MIN_WINDOWING_PHYSMEM=288
	MIN_GUI_INSTALL_PHYSMEM=512
	MIN_GUI_SYSID_PHYSMEM=512
else
	# on x86, ramdisk mini-root adds ~120Mb ramdisk
	MIN_INSTALL_PHYSMEM=184
	MIN_JAVA_INSTALL_PHYSMEM=504

	# unpacking all of X into memory takes up around 150Mb
	MIN_WINDOWING_PHYSMEM=400
	MIN_GUI_INSTALL_PHYSMEM=504
	MIN_GUI_SYSID_PHYSMEM=504
fi

# Free Virtual Memory Requirements. These numbers are
# checked against the output of /bin/mem which checks how
# much virtual memory is still available. This protects the
# installer from other things that might use more memory on
# a specific system.
#
MIN_WINDOWING_VIRTMEM=96
MIN_GUI_INSTALL_VIRTMEM=128
MIN_GUI_SYSID_VIRTMEM=128

export	MIN_WINDOWING_PHYSMEM \
	MIN_GUI_INSTALL_PHYSMEM MIN_GUI_SYSID_PHYSMEM \
	MIN_JAVA_INSTALL_PHYSMEM MIN_INSTALL_PHYSMEM
export	MIN_WINDOWING_VIRTMEM \
	MIN_GUI_INSTALL_VIRTMEM MIN_GUI_SYSID_VIRTMEM 

cd ${HOME}

#
# If the run level is changed after invocation, shell should
# be run
#
if [ -f /tmp/.sh ]; then
	echo "`gettext 'Exiting to shell...'`"
	exec ${SHELL}
else
	touch /tmp/.sh
fi

INSTALL_DEBUG=""
if [ -f "/tmp/.install_debug" ] ; then
    D=`head -1 /tmp/.install_debug`
    if [ "$D" = "install_debug" -o "$D" = "install_debug:all" ] ; then
	# turn on the world
	INSTALL_DEBUG="scripts,wizard"
    else
	case `echo $D | awk -F: '{print $1}'` in
	    install_debug)
		INSTALL_DEBUG=`echo $D | awk -F: '{print $2}'`
		;;
	    *)
		INSTALL_DEBUG=""
		;;
	esac
    fi
fi
export INSTALL_DEBUG

. /sbin/install-common
install_debug_settings
if install_debug_isset scripts ; then
    set -x
fi

#
#       checkmessage raw_device fstype mountpoint
#
# Simple auxilary routine to the shell function checkfs. Prints out
# instructions for a manual file system check before entering the shell.
#
checkmessage() {
        echo ""
        echo "WARNING - Unable to repair the $3 filesystem. Run fsck"
        echo "manually (fsck -F $2 $1). Exit the shell when"
        echo "done to continue the boot process."
        echo ""
}

checkmessage2() {
        echo ""
        echo "WARNING - fatal error from fsck - error $4"
        echo "Unable to repair the $3 filesystem. Run fsck manually"
        echo "(fsck -F $2 $1). System will reboot when you exit the shell."
}

#
# Main shell starts here
#
install_debug scripts "$0 begins `date`"

### CD into /tmp/root
cd ${HOME}
if [ -f $SWAPPART_FILE ];then
	### Mount the rootfs read,write.
	SWAPPART=`cat $SWAPPART_FILE`
	/usr/sbin/fsck -F ufs -m /dev/dsk/$SWAPPART > /dev/null 2>&1
	if [ $? -ne 0 ];then
		/usr/sbin/fsck -F ufs -o p /dev/dsk/$SWAPPART
		case $? in
			0|40)   # File system OK
				;;

			1|34|36|37|39)  # couldn't fix the file system - enter a shell
				checkmessage "/dev/dsk/$SWAPPART" "ufs" "/"
				/sbin/sulogin < /dev/console
				echo "resuming system initialization"
				;;
				
			*)      # fsck child process killed (+ error code 35)
				checkmessage2 "/dev/dsk/$SWAPPART" "ufs" "/" "$?"
				/sbin/sulogin < /dev/console
				echo "*** SYSTEM WILL REBOOT AUTOMATICALLY ***"
				sleep 5
				if [ `uname -p` = "sparc" ];then
					sync;sync;reboot -- `cat /.bootdev`
				else
					sync;sync;reboot
				fi
				;;
		esac
	fi
	mount -F ufs -o remount,rw / > /dev/null 2>&1
fi #check for swappart

# Add additional swap space from local disk if swap2 file exists.
if [ -f ${SWAP2_FILE} ];then
	swap -a ${SWAP2_FILE} > /dev/null 2>&1
fi


#
# Examine memory requirements
#

# get available virtual memory in megabytes
VIRTMEM=`/sbin/mem`; VIRTMEM=`expr $VIRTMEM / 1024`

# get total physical memory in megabytes
PHYSMEM=`/usr/sbin/prtconf | grep '^Memory size: ' | \
                sed -e 's/^Memory size: //' -e 's/ .*$//' `

MEMUNIT=`/usr/sbin/prtconf | grep '^Memory size: ' | \
                sed -e 's/^Memory size: [0-9][0-9]* //' `

case $MEMUNIT in
        Kilobytes) PHYSMEM=`expr $PHYSMEM / 1024` ;;
        Megabytes) ;;
        Gigabytes) PHYSMEM=`expr $TOTAL \* 1024` ;;
        Terabytes) PHYSMEM=`expr $TOTAL \* 1024 \* 1024` ;;
        *)         PHYSMEM=0 ;;
esac

export PHYSMEM

echo "install-setup available physical memory: ${PHYSMEM}" \
	>> /tmp/root/var/sadm/system/logs/sysidtool.log

echo "install-setup available virtual memory: ${VIRTMEM}" \
	>> /tmp/root/var/sadm/system/logs/sysidtool.log

install_debug scripts "install-setup available physical memory: ${PHYSMEM}" 
install_debug scripts  "install-setup available virtual memory: ${VIRTMEM}"

if [ "$PHYSMEM" -lt "$MIN_INSTALL_PHYSMEM" ] ; then
    echo "This installer requires a minimum of $MIN_INSTALL_PHYSMEM MB of physical memory"
    echo "to install.  This system only has $PHYSMEM MB of physical memory."
    echo
    echo "Exiting to shell. [Control-D will continue the installation]"
    ${SHELL}
fi

##########
# Install java into /tmp/root if java not already installed and
# we have enough virtual memory
if [ ! -x /usr/bin/java -a $PHYSMEM -ge $MIN_JAVA_INSTALL_PHYSMEM ] ; then
	install_debug scripts "Have enough physical memory to install java: ${PHYSMEM}"
	if [ -d /cdrom/Solaris_*/Product ] ; then
		echo "Setting up Java. Please wait..."
		install_debug scripts "Applying Java to miniroot..."
		create_admin /tmp/admin.$$

		OUTFILE=`install_debug_file scripts`

		/usr/sbin/pkgadd -n -R /tmp/root -d /cdrom/Solaris_*/Product \
			-a /tmp/admin.$$ SUNWj5rt >> ${OUTFILE:=/dev/null} 2>&1
	else
		install_debug scripts "Didn't find /cdrom/Solaris_*/Product"
	fi
else
	install_debug scripts "Don't have enough physical memory to install java: ${PHYSMEM}"
fi

# get available virtual memory in megabytes
VIRTMEM=`/sbin/mem`; VIRTMEM=`expr $VIRTMEM / 1024`

# minimum memory for a windowing, graphical system
if [ "$PHYSMEM" -lt "$MIN_WINDOWING_PHYSMEM" ] ; then
    echo "NOTE: Not enough memory for graphical installation.  Graphical installation"
    echo "      requires ${MIN_WINDOWING_PHYSMEM} MB of memory.  Found ${PHYSMEM} MB of memory."
    echo "      Reverting to text-based installation."
    touch /tmp/.nowin
elif [ "$VIRTMEM" -lt "$MIN_WINDOWING_VIRTMEM" ] ; then
    echo "NOTE: Not enough memory for graphical installation.  Graphical installation"
    echo "      requires ${MIN_WINDOWING_VIRTMEM} MB of virtual memory.  Found ${VIRTMEM} MB of virtual memory."
    echo "      Reverting to text-based installation."
    touch /tmp/.nowin
fi

# Check whether installing from the attached display
# if not set the install for text mode install

prtconf -v /devices | sed -n '/console/{;n;p;}' | grep tty > /dev/null
if [ $? = 0 ] ; then
	touch /tmp/.nowin
else
	prtconf -v /devices | sed -n '/output-device/{;n;p;}' | grep tty > /dev/null
	if [ $? = 0 ] ; then
		touch /tmp/.nowin
	else
		# Check whether the output device set to ttya or ttyb
		/usr/sbin/eeprom output-device | grep tty > /dev/null
		if [ $? = 0 ] ; then
			touch /tmp/.nowin
		fi
	fi
fi

cd /tmp/root/usr
#
# look for X in /boot first. If not there, look in Tools/Boot/miniroot_extra
# if it's not there, check Tools/Boot
#
if [ -f /tmp/.nowin ] ; then
	xcpio=/cdrom/boot/X_small.cpio.bz2
	if [ ! -f $xcpio ]; then
		toolsdir=/cdrom/Solaris_*/Tools
		bootdir=$toolsdir/Boot
		xcpio=$toolsdir/miniroot_extra/X_small.cpio.bz2
		if [ ! -f $xcpio ]; then
			xcpio=$bootdir/X_small.cpio.bz2
		fi
	fi
	if [ -f $xcpio ]; then
		install_debug scripts "Getting X_small archive from $xcpio"
		bzcat $xcpio | cpio -icdum 2> /dev/null
	else
		install_debug scripts "NOTICE: Cannot find X_small.cpio.bz2"
	fi
else
	xcpio=/cdrom/boot/X.cpio.bz2
	if [ ! -f $xcpio ]; then
		toolsdir=/cdrom/Solaris_*/Tools
		bootdir=$toolsdir/Boot
		xcpio=$toolsdir/miniroot_extra/X.cpio.bz2
		if [ ! -f $xcpio ]; then
			xcpio=$bootdir/X.cpio.bz2
		fi
	fi
	if [ -f $xcpio ]; then
		install_debug scripts "Getting X archive from $xcpio"
		echo "Extracting windowing system. Please wait..."
		bzcat $xcpio | cpio -icdum 2> /dev/null
	else
		install_debug scripts "NOTICE: Cannot find X.cpio.bz2"
	fi
fi
cd /tmp/root

# Export net boot configuration strategy. _INIT_NET_IF is set to the
# interface name of the netbooted interface if this is a net boot.
# _INIT_NET_STRATEGY is set to the network configuration strategy.
# First use netbootinfo and if that fails use the legacy netstrategy
_INIT_NET_STRATEGY=`${NETBOOTINFO} net-config-strategy 2>/dev/null`

if [ $? -eq 0 -a ${_INIT_NET_STRATEGY}X != "noneX" ]; then
	Roottype=`${NETBOOTINFO} rootfs-type`
	if [ $? -ne 0 ]; then
		Roottype=""
	fi

	_INIT_NET_IF=`${NETBOOTINFO} interface-name`
	if [ $? -ne 0 ]; then
		_INIT_NET_IF=""
	fi
	if [ "X${_INIT_NET_IF}" != "X" ] ; then
	    # we must have net booted
	    Network=yes
	fi
else
	_INIT_NET_STRATEGY=""
        set -- `/sbin/netstrategy`
        if [ $? -eq 0 ]; then
                if [ "$1" = "nfs" -o "$1" = "cachefs" ]; then
                        _INIT_NET_IF="$2"
                fi
                _INIT_NET_STRATEGY="$3"
                export _INIT_NET_IF _INIT_NET_STRATEGY 
        fi
fi

export _INIT_NET_IF _INIT_NET_STRATEGY
install_debug scripts "%s set to %s" _INIT_NET_STRATEGY  "$_INIT_NET_STRATEGY"
install_debug scripts "%s set to %s" _INIT_NET_IF  "$_INIT_NET_IF"

##########
# Make sure all configuration necessary is completed in order
# to run the window system

# determines if we are on the locale console, or
# on a serial console (i.e. tip'd into ttya)
# if we are, we know what the terminal type should
# be.
if [ -x /sbin/getconsole ] ; then
    CONSOLE_TERM=`/sbin/getconsole`
    if [ $? = 0 ] ; then
	ON_CONSOLE=$YES
	TERM=$CONSOLE_TERM;export TERM
    else 
	ON_CONSOLE=$NO
    fi
else
    # assume we aren't on the console,
    # so termtype questions get asked if needed.
    # 
    ON_CONSOLE=$NO
fi

export ON_CONSOLE

# Enable the system/system-log and system/cryptosvc services here.
# These two services have to be manually enabled because they are
# disabled by default in their manifests.
/usr/bin/cp /etc/syslog.conf.install /tmp/root/etc/syslog.conf >/dev/null 2>&1
/usr/bin/touch /tmp/install_log.syslog >/dev/null 2>&1
/usr/sbin/svcadm enable -t system-log >/dev/null 2>&1
/usr/sbin/svcadm enable -t cryptosvc >/dev/null 2>&1

echo "`gettext 'Beginning system identification...'`"

# This has to be "dotted" in because sysid-setup sets environment variables
# that we want things down the line to see, like LC_MESSAGES and LC_ALL
. /sbin/sysid-setup

if [ -f /tmp/.nowin ] ; then
    RUN_WIN=no
    RUN_TEXT_INSTALL=yes
else
    RUN_WIN=yes
    if [ ! -x /usr/bin/java ] ; then
	RUN_TEXT_INSTALL=yes
    else
	RUN_TEXT_INSTALL=no
    fi
fi

if [ -f /tmp/.text_install ] ; then
    RUN_TEXT_INSTALL=yes
fi

export	RUN_WIN RUN_TEXT_INSTALL INSTALL_DEBUG INSTALL_LOG \
	INSTALL_CONSOLE

# Start up the window system unless the display device cannot be
# determined or the install process with explicitly booted with
# the "-nowin" option.
#

install_debug scripts "$0 completes `date`"
exec /sbin/install-ui-start 
