#!/bin/sh

usage() {
    program=`basename $0`

    echo "Usage: $program <platform> <TEST | EXTENDED> package"
    echo "  platform      <Optional> hardware must be this platform."
    echo "  TEST          Perofrm read/write testing of compact flash memory."
    echo "  EXTENDED      Perform extended testing of compact flash memory."
    echo "  package       Package to install."

    echo ""
    echo "Platform \"$PLATFORM\" packages are:"
    ls ./$PLATFORM/*.plist 2>/dev/null | cut -d"/" -f3 | cut -d "." -f1
    exit 1
}

exit_out()
{
    if [ $error = TRUE ]
    then
	echo "SCRIPT: install FAILED with $warn_count warnings."
	exit 1
    else
	if [ $warn_count -gt 0 ]
	then
	    echo "SCRIPT: install PASSED with $warn_count warnings."
	else
	    echo "SCRIPT: install PASSED."
	fi
	exit 0
    fi
}

#
# do_command <warn/error> <command...>
#
do_command()
{
    warn=$1
    shift
    $*
    if [ $? -ne 0 ]
    then
	if [ $warn = TRUE ]
	then
	    echo "SCRIPT: Warning - failed $0 $*"
	    warn_count=`expr $warn_count + 1`
	    return 1
	else
	    echo "SCRIPT: ERROR - failed *0 $*"
	    continue=FALSE
	    error=TRUE
	    exit_out
	fi
    fi
    return 0
}
#
# install-rpms <plist> <root>
#
installrpms()
{
    LIST=$PLATFORM/$1

    if [ ! -f $LIST ] || [ ! -r $LIST ]; then
	echo "SCRIPT: Cannot open/read package list to install."
	exit 1
    fi

    if [ ! -z $2 ]; then
	ROOT=$2
    else
        ROOT=/
    fi

    RPM="rpm --root $ROOT"

    echo "SCRIPT: Installing RPMs from $LIST rooted at $ROOT..."

    if [ ! -d ${ROOT}/var/lib/rpm ]; then
        echo "SCRIPT: Initializing RPM database..."
	do_command FALSE mkdir -p ${ROOT}/var/lib/rpm
	do_command FALSE rpm --root $ROOT --initdb
    fi

    for package in `cat $LIST | dd skip=18 bs=16 2> /dev/null | grep -v '#' | xargs`;
    do
	#
	# Only install the package if it hasn't already been installed
	# 
#	if ! $RPM -q `echo $package | sed -e "s,\([[:graph:]]\+-[.[:alnum:]]\+-[[:alnum:]]\+\)\.\([[:alnum:]]\+\)\.\(rpm\),\1,g"` > /dev/null 2>&1; then
	    do_command TRUE $RPM --force --nodeps -ivUh $package
	    if [ $? -ne 0 ]
	    then
		do_command FALSE $RPM --force --nodeps -ivUh $package
	    fi
#	fi
    done
}
#
# test_for_package <candidate>
#
test_for_package()
{
    abc=`echo $1 | tr -s '[:upper:]' '[:lower:]'`

    #
    # See if first parameter was a PACKAGE
    #
    if [ -f ./$PLATFORM/$abc.plist ]
    then
	echo $abc
    else
	echo FALSE
    fi
}
#
# test_for_test <candidate>
#
test_for_test()
{
    if [ "$1" = "TEST" ]
    then
	echo 1
    else
	if [ "$1" = "EXTENDED" ]
	then
	    echo 2
	else
	    echo FALSE
	fi
    fi
}

#
# parse the command line arguments
#
parse_arguments()
{
    # check explicitly for package and test parameters, and assume 
    # anything else is the plaftorm validation
    #
    while [ $# -gt 0 ]
    do
	result=`test_for_package $1`
	if [ "$result" = "FALSE" ]
	then
	    result=`test_for_test $1`
	    if [ "$result" = "FALSE" ]
	    then
		#
		# Translate across the soft link if it is a link
		#
		TARGET_PLATFORM=$1
		target=`ls -l $TARGET_PLATFORM 2>/dev/null | grep "^l"`
		if [ "$target" != "" ]
		then
		    TARGET_PLATFORM=`ls -l $TARGET_PLATFORM | cut -d"/" -f2`
		fi
		if [ -z $PLATFORM ]
		then
		    if [ ! -d ./$TARGET_PLATFORM ]
		    then
			echo "SCRIPT: Unknown Platform specified $TARGET_PLATFORM"
			usage
		    fi
		    PLATFORM=$TARGET_PLATFORM
		    case $PLATFORM in
			"SWBD10" ) REVISION=0;;
			"SWBD12" ) REVISION=3;;
			*) REVISION=0;;
		    esac
		fi
	    else
		do_test=$result
	    fi
	else
	    PACKAGE=$result
	fi
	shift
    done
}

#------------------------------
# BEGIN MAIN PART OF THE SCRIPT
# BEGIN MAIN PART OF THE SCRIPT
#------------------------------

if [ -z `pwd | grep load` ]
then
    echo "SCRIPT: ERROR install directory is not mounted on /load."
    exit 1
fi

for mnt in `mount | cut -d" " -f3 | grep "/mnt"`
do
    umount $mnt
done

FS='xfs'
FSOPTS='-f'
DEVICE='hda'
TMPMNT='/mnt'
do_test=NOTEST
warn_count=0
continue=TRUE
error=FALSE

echo "SCRIPT: Installing new NFS root packages..."
PLATFORM="."
PACKAGE="no_package_defined"
node="platform"
major=`grep $node\$ /proc/devices | cut -d ' ' -f 1`
if [  $major ]; then
    rm -f /dev/$node
    mknod --mode=644 /dev/$node c $major 0
fi

if [ ! -f /bin/sin ]
then
     # fixing up the links and directories for installation of net.plist
     if [ ! -d /fabos ]
     then
         mkdir /fabos
     fi
     if [ ! -d /fabos/lib ]
     then
         mkdir /fabos/lib
     fi
     if [ ! -f /lib/libdb.so ]
     then
         ln -s /lib/libdb.so.3 /lib/libdb.so
     fi
     if [ ! -d /boot ]
     then
         mkdir /boot
     fi
     cp ./System.map /boot/System.map
     chmod 777 /boot/System.map
     installrpms net.plist
fi

PLATFORM=`sin | \
		  /bin/grep Platform | \
		  /usr/bin/cut -d" " -f2 | \
		  /usr/bin/cut -d"," -f1`

REVISION=`sin | \
		  /bin/grep Platform | \
		  /usr/bin/cut -d" " -f4`

TARGET_PLATFORM=$PLATFORM
######################
# parse the arguments
#
parse_arguments $*

XFS=FALSE
case "$PLATFORM" in
    "SWBD10" ) XFS=TRUE;;
    "SWBD12" ) 
	case $REVISION in
	    1|2|3) XFS=TRUE;;
	esac
esac

#######################
# Check the parameters
#
if [ ! -f ./$PLATFORM/$PACKAGE.plist ]
then
    printf "SCRIPT: Incorrect package %s\n" $PACKAGE
    usage
fi
if [ $PLATFORM != $TARGET_PLATFORM ]
then
    echo "SCRIPT: Actual platform ($PLATFORM) does not match specified platform $TARGET_PLATFORM."
    echo "SCRIPT: ERROR - failed $0 $*"
    continue=FALSE
    error=TRUE
    exit_out
fi

##############################################
# Let's get down to it and install this thing
#
echo "SCRIPT: INSTALLING for platform: $PLATFORM revision: $REVISION package $PACKAGE"

echo "SCRIPT: Finding module dependencies..."

if [ ! -h /lib/modules/`uname -r` ]; then
	ln -sf default /lib/modules/`uname -r`
fi

do_command FALSE depmod -Aqe

do_command FALSE chkconfig pcmcia on

if [ "$XFS" = TRUE ]
then
    echo "SCRIPT: Starting services..."

    do_command FALSE /etc/rc.d/init.d/pcmcia start
fi

max_count=30
echo -n "SCRIPT: Determining drive capacity (MAX $max_count sec)"

count=0
while [ ! -f /proc/ide/${DEVICE}/capacity -a $count -lt $max_count ]; do
	echo -n "."
	sleep 1
	count=`expr $count + 1`
done
echo ""
if [ $count -ge $max_count ]
then
    echo "SCRIPT: Failed to determine drive capacity. Perhaps pcmcia driver did not start correctly."
    error=TRUE
    exit_out
fi


echo "SCRIPT: Partitioning drive..."

BLOCKS=`cat /proc/ide/${DEVICE}/capacity`
((BYTES = BLOCKS * 512))
((HALFB = BYTES / 2))
((HALFMB = HALFB >> 20))
((ENDMB = 2 * HALFMB))

do_command FALSE parted -s /dev/${DEVICE} mklabel msdos
do_command FALSE parted -s /dev/${DEVICE} mkpart primary $FS 0.000 $HALFMB.000
do_command FALSE parted -s /dev/${DEVICE} mkpart primary $FS $HALFMB.000 $ENDMB.000
do_command FALSE parted -s /dev/${DEVICE} print

for partition in 1 2; do
  if [ $continue = TRUE ]
  then
    #
    # if this is a Ulysses box, then program the backplane mac address
    #
    if [ ${partition} -eq 1 ]
    then
	if [ -f ./$PLATFORM/bpmac ]
	then
	    echo "SCRIPT: Setting up Private Ethernet mac address"
	    do_command FALSE ./$PLATFORM/bpmac
	fi
    fi

    echo "SCRIPT: Creating $FS file system on /dev/${DEVICE}${partition}..."

    do_command FALSE mkfs -t $FS $FSOPTS /dev/${DEVICE}${partition}

    if [ "$do_test" = NOTEST ]
    then
	echo "SCRIPT: Skipping the memory tests"
    else
	if [ "$do_test" = 1 ]
	then
	    echo "SCRIPT: Running the Read/Write memory tests"
	else
	    echo "SCRIPT: Running the EXTENDED memory tests"
	fi
	./sbin/blockcheck -t $do_test /dev/${DEVICE}${partition}
	echo "SCRIPT: Recreating $FS file system on /dev/${DEVICE}${partition}..."

	do_command FALSE mkfs -t $FS $FSOPTS /dev/${DEVICE}${partition}

    fi

    echo "SCRIPT: Mounting primary file system on ${TMPMNT}..."

    do_command FALSE mount -t $FS /dev/${DEVICE}${partition} ${TMPMNT}

    #
    # Install soft-link for modules
    #
    do_command FALSE mkdir /mnt/lib
    do_command FALSE mkdir /mnt/lib/modules
    do_command FALSE ln -sf default /mnt/lib/modules/`uname -r`

    #
    # Make sure groups are installed.
    #
    do_command FALSE mkdir /mnt/etc
    do_command FALSE cat > /mnt/etc/group << EOF
root::0:root
bin::1:root,bin,daemon
daemon::2:root,bin,daemon
sys::3:root,bin,adm
EOF
    #
    # Create fabos/lib
    #
    do_command FALSE mkdir /mnt/fabos
    do_command FALSE mkdir /mnt/fabos/lib

    #
    # Fix termcap / readline chicken and egg problem
    #
    do_command FALSE cp /lib/libtermcap.so.1 /mnt/lib

    installrpms $PACKAGE.plist ${TMPMNT}

    ####################################
    # Run platform specific install if required
    if [ -f $PLATFORM/install ]
    then
	echo "SCRIPT: Running $PLATFORM/install"
	$PLATFORM/install $PLATFORM $PACKAGE
    fi

    ####################################
    # load the manufacturing additions
    # After the normal rpm's and PLATFORM specific process has been completed,
    # then install the manufacturing overlays it they exist. We must be 
    # specific, and only take this action if the PACKAGE is factory or 
    # development. DO NOT do this for the release SW.

    if [ "$PACKAGE" = factory -o "$PACKAGE" = development ]
    then
	for fil in `ls ./$PLATFORM/Mfgtests/*/* 2>/dev/null`
	do
	    script=`echo $fil | cut -d"/" -f4-`
	    echo "SCRIPT: Loading $script"
	    do_command FALSE cp $fil /mnt/fabos/$script
	    do_command FALSE chmod 0755 /mnt/fabos/$script
	    do_command FALSE chgrp factory /mnt/fabos/$script
	    # if there are additions for manufacturing, then the rpm -V that 
	    # happens during boot (controlled by the NoSysTest boot 
	    # environment variable) will most likely fail, so turn of the
  	    # the rpm -V (only once though).
	done
    fi

    echo "SCRIPT: Updating the file system table..."

    cat > ${TMPMNT}/etc/fstab << EOF
/dev/root	/		$FS	rw,noatime	0 0
none		/proc		proc	defaults	0 0
none		/dev/pts	devpts	mode=620	0 0
EOF

    echo "SCRIPT: Fixing up pdm wrong directory for rcp"
    do_command FALSE ln -sf ../usr/bin/rcp /mnt/bin/rcp

    echo "SCRIPT: Fixing up /etc/modules.conf..."

    do_command FALSE cat > /mnt/etc/modules.conf << EOF
keep
path=/fabos/modules
alias eth1 eepro100
EOF

    echo "SCRIPT: Fixing fabos/sbin/sname"
    if [ ! -x /mnt/fabos/sbin/sname ] ; then
          ln -sf ../bin/sname /mnt/fabos/sbin/sname
    fi

    echo "SCRIPT: Creating release file"
    do_command FALSE ./sbin/create_release_file -p $PLATFORM -l $PACKAGE

    #
    # Remove circular link.
    #
    echo "SCRIPT: Remove circular link in /lib/modules"

    rm /mnt/lib/modules/`uname -r`/default 2>/dev/null 1>&2

    if [ "$PACKAGE" = factory ]
    then
	echo "SCRIPT: Fixing up /etc/config entries..."

	# only turn off fabos on the first partition
	# This allows manufacturing process to use xtool on clean install
	# and having the second partition on allows for badrootdev support
	# during power cycle tests.
	if [ ${partition} -eq 1 ]
	then
	    do_command FALSE rm -f /mnt/etc/config/fabos  2>/dev/null
	    do_command FALSE echo "off" > /mnt/etc/config/fabos
	fi
	# turn off the login timeout
	do_command FALSE cat > /mnt/etc/idle.conf << EOF
0
EOF
	do_command FALSE rm -f /mnt/etc/config/webtools 2>/dev/null
	do_command FALSE rm -f /mnt/etc/config/fwd 2>/dev/null
	do_command FALSE rm -f /mnt/etc/config/evmd 2>/dev/null
	do_command FALSE rm -f /mnt/etc/config/snmpd 2>/dev/null
	do_command FALSE rm -f /mnt/etc/config/swdd 2>/dev/null
	do_command FALSE rm -f /mnt/etc/config/wdtd 2>/dev/null

	do_command FALSE echo "off" > /mnt/etc/config/webtools
	do_command FALSE echo "off" > /mnt/etc/config/fwd
	do_command FALSE echo "off" > /mnt/etc/config/evmd
	do_command FALSE echo "off" > /mnt/etc/config/snmpd
	do_command FALSE echo "off" > /mnt/etc/config/swdd
	do_command FALSE echo "off" > /mnt/etc/config/wdtd
    fi

    ####################################
    # Copy kernel image to user flash only once
    #
    if [ ${partition} -eq 1 ]
    then
	echo "SCRIPT: Writing the kernel image to user flash"

	do_command FALSE /sbin/flash_write -i /mnt/boot/zImage.tree.initrd -o /dev/mtd3
	do_command FALSE /sbin/flash_write -i /mnt/boot/zImage.tree.initrd -o /dev/mtd4
    fi

    echo "SCRIPT: Unmounting file system..."

    do_command FALSE umount ${TMPMNT}
  fi
done

####################################
# Update boot environment
#
echo "SCRIPT: Setting boot environment parameters..."
# remove the system test override variable
# NOTE do not use do_command on this because the variable may not exist,
# and the command will return a fail status, but this is not an indication
# of a failing install
bootenv -u NoSysTest 2> /dev/null

# The special characters in this bootenv variable value prevent the use of 
# do_command. So I have copied the content of do_command here.
bootenv -u LoadIdentifier
bootenv -v LoadIdentifiers "IDE w/ XFS;IDE w/ XFS & NFS Root"

do_command FALSE bootenv -v OSLoader 'MEM()0xF0000000;MEM()0xF0800000'
do_command FALSE bootenv -v OSRootPartition "${DEVICE}1;${DEVICE}2"
do_command FALSE bootenv -v AutoLoad 'yes'
do_command FALSE bootenv -v InitTest 'MEM()'
do_command FALSE bootenv -v SkipWatchdog 'yes'
# NOTE do not use do_command on this because the variable may not exist,
# and the command will return a fail status, but this is not an indication
# of a failing install
bootenv -u BadRootDev 2> /dev/null

####################################
# Output ending instructions
#
if [ -f $PLATFORM/ending_instructions ]
then
    cat $PLATFORM/ending_instructions
else
    echo ""
    echo "SCRIPT: No platform specific instructions found."
    echo "SCRIPT: You may now reboot the system."
    echo ""
    echo "SCRIPT: Be sure you have a console connection to the system before rebooting."
    echo ""
fi
####################################
# Output overall results
#
exit_out
