#!/bin/sh

######################################################################
# Find the latest version of a package
# in: $1      The name of a package (e.g. "monitor")
#out: LATEST  The latest version of that package in the directory
#             without the .Z
#note assumes the package looks like this D3_packagename-imp-mag.min.rel-.Z
#     where packagename is the name of the package (e.g. monitor)
#			imp			is the implementation (e.g. rs)
#			maj			is the major release
#			min			is the minor release
#			rel			is the release level *FOR THIS PKG* (the 65 in M65)
######################################################################
findLATEST(){
	LATEST=`cd $INSTDIR; ls D3_$1-$IMP-* 2>/dev/null	| awk -F- ' \
		BEGIN{	split("0.0.0",max,".");\
			fudge=length("'$SUFFIX'")-1;}\
		{\
			split($3,ver,".");\
			for(i=1;i<=3;i++){\
				if (ver[i]>max[i]) {\
					max[1]=ver[1];\
					max[2]=ver[2];\
					max[3]=ver[3];\
					maxfile=$0;\
				}\
			}\
		}\
		END{ print substr(maxfile,1,length(maxfile)-(2+fudge)) }'`
}

# DoEcho - A generic version of echo
# ----------------------------------
DoEcho()
{
	if [ "$1" = "-n" ]; then
		if [ "$IMP" = "rs" ]; then
			OutStr="$2"
			echo "$OutStr"
		fi
		if [ "$IMP" = "lx" ]; then
			echo -n $2
		fi
	else
		echo "$1"
	fi
}

UpdateShmMax()
{
  SHMMAX=536870912

  CURRSHMMAX=`cat /proc/sys/kernel/shmmax`

  if [ $CURRSHMMAX -lt $SHMMAX ]; then
	echo "" >> /etc/sysctl.conf
	echo "# Nex maximum shred segment size for D3" >> /etc/sysctl.conf
	echo "kernel.shmmax = $SHMMAX" >> /etc/sysctl.conf
	sysctl -q kernel.shmmax=$SHMMAX
  fi

}



# GetVer - Convert /etc/redhat-release to version numbers
# -------------------------------------------------------
GetVer()
{
	MAJ=$1
	MIN=$2

	FILE="/etc/redhat-release"
	STR=$(cat ${FILE})

	grep "pdate" ${FILE} > /dev/null 2>&1
	res=$?

	TMP1=${STR##*release }
	MAJ=$(echo ${TMP1} | cut -c 1)

	if [ "$res" = "0" ]
	then
		TMP2=${STR##*pdate }
		MIN=$(echo ${TMP2} | cut -d " " -f 1|cut -d "." -f 2)
	else
		MIN=$(echo ${TMP1} | cut -d " " -f 1|cut -d "." -f 2)
	fi
	DISTRIB=$(echo ${STR} |								\
		sed -e "s/[[:blank:]][Ll][Ii][Nn][Uu][Xx][[:blank:]]/ /g"	\
		-e "s/\(.*\)[[:blank:]]release.*/\1/" -e "s/[[:blank:]]//g")

}

# Link the the d3zip and d3unzip to either gzip or compress/unxompress
# return 0 on success or 1 on failure.
# --------------------------------------------------------------------
LinkZips()
{           
	RetVal=0
	PickBase=/usr/lib/pick
	D3zip=${PickBase}/d3zip
	D3unzip=${PickBase}/d3unzip
	InsStat="/tmp/d3.install.stat"

	# Check for existing d3zip, if found leave them alone
	# ---------------------------------------------------
	if [ -x "${D3zip}" ]; then
		echo "${D3zip} exists, leaving ${D3zip} unmodified. " >> ${InsStat}
		return 1
	fi

	# Look for zip, if found set paths for gzip,gunzip else compress,uncompress
	# -------------------------------------------------------------------------
	Pzip=`which gzip`
	ret=$?
	if [ $ret -eq 0 ]; then
		# we'll use gzip for both compressing ans uncompressing
		Punzip=${Pzip}
	else
		# didn't find gzip using compress and uncompress
		Pzip=`which compress`
		Punzip=`which uncompress`
	fi

	# Link the zip command
	# --------------------
	echo "${D3zip} is being linked to ${Pzip} " >> ${InsStat}
	ln -s ${Pzip} ${D3zip}
	ret=$?
	if [ $ret -ne 0 ]; then
		echo "Unable to create link to ${Pzip}"
		RetVal=1
	fi

	# Link the unzip command
	# ----------------------
	echo "${D3unzip} is being linked to ${Punzip} " >> ${InsStat}
	ln -s ${Punzip} ${D3unzip}
	ret=$?
	if [ $ret -ne 0 ]; then
		echo "Unable to create link to ${Punzip}"
		RetVal=1
	fi

	return ${RetVal}
}

#Find out about the environment
CWD=`pwd`
INSTDIR=`dirname $0`
[ "$INSTDIR" = "." ] && INSTDIR=$CWD
IMP=*
findLATEST "install"
IMP=`(cd $INSTDIR; ls $LATEST* | awk -F- '{print $2}')`
TERMTYPE=$TERM
ABANDON=5

if [ "$IMP" = "lx" ]; then
	if [ ! -x "/usr/bin/uncompress" ]; then
		ln -s /usr/bin/gunzip  /usr/bin/uncompress
		ret=$?
		if [ $ret -ne 0 ]; then
			echo "ERROR:unable to link gunzip to uncompress"
			exit 4
		fi
	fi

	# Check for correct RedHat version
	# --------------------------------
	GetVer MAJ MIN
	skip=0

	if [ "$MAJ" = "3" ]
	then
		skip=1
	fi

	if [ "$MAJ" = "4" ]
	then
		skip=1
	fi

	if [ "$MAJ" = "5" ]
	then
		if [ $MIN -lt 1 ]
		then
			skip=1
		fi
	fi


	if [ "$skip" = "1" ]
	then
		echo "D3 can not run on the installed version of Red Hat, please check the"
		echo "release notes for the correct version of Red Hat Enterprise Linux"
		exit
	fi
	
	DEPFILE=/usr/lib/pick/d3depends
	if [ ! -f "${DEPFILE}" ]
	then
		echo "Checking for dependencies... This could take a little bit of time."
		# Check for required dependencies
		# -------------------------------
		YUMFILE="/etc/yum.repos.d/d3depends.repo"
		export YUM0=${DISTRIB}/${MAJ}.${MIN}
		echo "[d3depends]" > $YUMFILE
		echo "name=d3depends for RHEL/ CentOS \$releasever - \$basearch [\$YUM0]" >> $YUMFILE
		echo "baseurl=ftp://d3mv-repo:d3getRep0@ftp.rocketsoftware.com/$YUM0/\$basearch" >> $YUMFILE
		echo "enabled=1" >> $YUMFILE
		echo "gpgcheck=0" >> $YUMFILE
		echo "gpgkey=" >> $YUMFILE
		echo "protect=1" >> $YUMFILE

		rpm -ql d3depends >/dev/null 2>&1
		if [ $? -eq 0 ]
		then
			REINS=reinstall
		else
			REINS=install
		fi
		yum --disablerepo=\* --enablerepo d3depends $REINS d3depends

		# Check for type of d3depends file
		# --------------------------------
		if [ -f "${DEPFILE}" ]; then
			DEPID=`sed -n 1,1p ${DEPFILE}|cut -d" " -f1`
			if [ $DEPID = d3depends ]; then
	
				# Load packages from list in d3depends file
				# -----------------------------------------
				for DEPPKG in `sed -n 2,2p ${DEPFILE}`
				do
			 		yum -y --disablerepo=\* --enablerepo d3depends install $DEPPKG
				done
			fi
		fi

		rm -rf $YUMFILE
	fi
fi

### [12] begin ###

#Find out if there are existing d3 or ap processes running before installing.
if [ "$IMP" = "lx" ]
then
 GETPID=`ps auwx | grep -v " ap | d3 | pick " | awk '$0 ~ / ap | d3 | pick / {print}'`
else
 GETPID=`ps -ef | grep -v " ap | d3 | pick " | awk '$0 ~ / ap | d3 | pick / {print}'`
fi

if [ "$GETPID" != "" ]
then
	echo
	echo There may be some d3/ap processes running:
	echo
	if [ "IMP" = "lx" ]
	then
 ps auwx | grep -v " ap | d3 | pick " | awk '$0 ~ / ap | d3 | pick / {print}'
	else
 ps -ef | grep -v " ap | d3 | pick " | awk '$0 ~ / ap | d3 | pick / {print}'
	fi
	echo
	if [ "$IMP" = "lx" ]
	then
         echo -n "Do you want to continue with the installation (Type y<return> to continue)? "
	else
         echo -n "Do you want to continue with the installation (Type y<return> to continue)? "
	fi
	read CONT
	if [ "$CONT" = "Y" -o "$CONT" = "y" ]
	then
         :
	else
         echo
         echo Installation aborted.
         echo
         exit 1
	fi
else
	ipcrm -M 0xd3acd1b8 >/dev/null 2>&1
fi

### [12] end ###

# Do we ask the install questions?
# --------------------------------
ASK=Y
[ -r /tmp/D3INSTALLDA ] && ASK=N

[ $IMP = "lx" ] && SUFFIX=Z || SUFFIX=Z   # [06]
[ $IMP = "lx" ] && UNCOMPRESS="gunzip" || UNCOMPRESS=uncompress  # [06]

# Main Script

findLATEST "abs"
ABS=$LATEST

findLATEST "datafiles"
DAT=$LATEST

findLATEST "flash"
FLA=$LATEST

findLATEST "install"
INS=$LATEST

findLATEST "monitor"
MON=$LATEST

findLATEST "sql"
SQL=$LATEST

findLATEST "ati"
ATI=$LATEST

findLATEST "fsi"
FSI=$LATEST

# Check to make sure I can find all of my files
FILES="D3_ssn D3_setup D3_setup_mv D3_copyright D3_ugf"
[ $IMP = "rs" ] && FILES="$FILES D3_data"

# If Linux update the kerner.shmmax value
# ---------------------------------------
if [ "$IMP" = "lx" ]; then
  UpdateShmMax
fi


for FILE in $FILES
do
	if [ ! -r $INSTDIR/$FILE ]
	then
		echo Unable to read $INSTDIR/$FILE!  Installation cannot
		echo proceed.
		exit 1
	fi
done

echo The following installation files will be used:
echo "abs:       " $ABS.$SUFFIX
echo "datafiles: " $DAT.$SUFFIX
echo "flash:     " $FLA.$SUFFIX
echo "install:   " $INS.$SUFFIX
echo "monitor:   " $MON.$SUFFIX
echo "sql:       " $SQL.$SUFFIX
[ -f $FSI.$SUFFIX ] && echo "FSI:       " $FSI.$SUFFIX
[ -f $ATI.$SUFFIX ] && echo "openMV:    " $ATI.$SUFFIX
echo
echo Welcome to the D3 installation procedure.	You have successfully installed
echo the distribution files.
echo
echo The distribution files are used to build the D3 environment on your
echo UNIX machine.	When the installation process completes successfully,
echo it can delete the distribution files, or leave them on the local
echo hard disk so you can install D3 onto other UNIX machines on your
echo Local Area Network without re-installing the media.
echo
echo "Do you want to delete the distribution files when the installation"
echo -n "routine is finished with them? "
DELETE=n
[ "$ASK" = "Y" ] && read DELETE
[ "$DELETE" = "Y" ] && DELETE=y

echo
echo  When the install completes, the distribution files will
[ "$DELETE" != "y" ] && echo -n "NOT "
echo be deleted.
echo
echo After this procedure, you must run the "d3" command to complete the
echo installation as described in the installation manual.
echo
echo -n "Do you want to continue the installation? "
CONTINUE=Y
[ "$ASK" = "Y" ] && read CONTINUE
[ "$CONTINUE" = "Y" ] && CONTINUE=y

if [ "$CONTINUE" != "y" ]
then
	echo "You have chosen to abort the installation."
	exit 1
fi

if [ $IMP = "rs" ]
then
	LIBDIR=/usr/lpp/pick
	INSTAL_PICK_DIR=$LIBDIR

	# -X option for installp.	First try without it
	XOPTION=""

	# What did installp return?
	INSTALLPERR=""

	# Tell installp to install my package
	while [ "$INSTALLPERR" != 0 ]
	do
		rm -f /tmp/ap.installerr
		installp $XOPTION -d $INSTDIR/D3_data -Fa pick 2> /tmp/ap.installerr
		INSTALLPERR=$?
		if [ "$INSTALLPERR" != 0 ]
		then
			# If this is the second time thru (XOPTION=-X) & we still can't
			# install, then there just isn't enough space -- abort
			if [ "$XOPTION" = "-X" ]
			then
				echo D3_setup: INSTALLATION ERROR
				echo The Installation has failed.  To retry the installation
				echo when the problem has been resolved, run the D3_setup
				echo script again.	The first part of the /tmp/ap.installerr
				echo file will print below:
				head -15 /tmp/ap.installerr
				exit 1
			fi
			echo D3_setup: INSTALLATION ERROR
			echo There may not be enough space in the root or usr file system
			echo to install D3. D3_setup can attempt to compensate by re-
			echo executing the install with an option to automatically allocate
			echo more space from a pool of free space.	Alternatively, you can
			echo examine the /tmp/ap.installerr file to determine which file
			echo system needs more space and remove or relocate files as 
			echo necessary.
			echo
			echo -n "Do you want to automatically allocate space? "
			COMPENSATE=Y
			[ "$ASK" = "Y" ] && read COMPENSATE
			[ "$COMPENSATE" = "Y" ] && COMPENSATE=y

			if [ "$COMPENSATE" != "y" ]
			then
				echo The installation has been ABORTED.  Once you have corrected
				echo the problem, you can restart the installation with the
				echo D3_setup script.
				exit 1
			else
				echo Re-executing the installp with the -X option...
				XOPTION=-X
			fi
		fi
	#while
	done
elif [ $IMP = "s5" ]
then
	LIBDIR=/usr/lib/pick
	mkdir $LIBDIR 2> /dev/null
	INSTAL_PICK_DIR=/tmp

	# Check for single user mode
	# --------------------------
	RLEVEL=`who -r | awk '{print $3}'`
	if [ ! "$RLEVEL" = "S" ]
	then
		echo
		echo The system is not currently in single user mode
		echo This may create problems later during the installation.
		echo -n "Do you want to continue anyway (Type y<return> to continue) ? "
		DUMMY=y
		[ "$ASK" = "Y" ] && read DUMMY
		[ "$DUMMY" = "Y" ] && DUMMY=y

		if [ "$DUMMY" != "y" ]
		then
			exit 1
		fi
	fi
elif [ $IMP = "lx" ]
then
	LIBDIR=/usr/lib/pick
	mkdir $LIBDIR 2> /dev/null
 INSTAL_PICK_DIR=$LIBDIR
elif [ $IMP = "sun" ]
then
	LIBDIR=/usr/lib/pick
	mkdir $LIBDIR 2> /dev/null
 INSTAL_PICK_DIR=$LIBDIR
elif [ $IMP = "uw" ]
then
 LIBDIR=/usr/lib/pick
 mkdir $LIBDIR 2> /dev/null
 INSTAL_PICK_DIR=$LIBDIR
elif [ $IMP = "hp" ]
then
	LIBDIR=/usr/lib/pick
	mkdir $LIBDIR 2> /dev/null
	INSTAL_PICK_DIR=$LIBDIR
fi

# make the pick_term directory
# ----------------------------
if [ ! -d "${LIBDIR}/pick_term" ]		# [16]
then									# [16]
	mkdir ${LIBDIR}/pick_term			# [14] 
	chmod a+rwx ${LIBDIR}/pick_term		# [14]
fi										# [16]

# unpack the install and monitor packages
cd $LIBDIR
$UNCOMPRESS -c $INSTDIR/$INS.$SUFFIX | tar xf -
$UNCOMPRESS -c $INSTDIR/$MON.$SUFFIX | tar xf - >/dev/null 2>&1

[ -f $ATI.$SUFFIX ] && $UNCOMPRESS -c $INSTDIR/$ATI.$SUFFIX | tar xf -
[ -f $FSI.$SUFFIX ] && $UNCOMPRESS -c $INSTDIR/$FSI.$SUFFIX | tar xf -
cd $CWD

# move pieces where they belong
$INSTDIR/D3_setup_mv

# Make flash & sql packages available to install
cp $INSTDIR/$FLA.$SUFFIX $LIBDIR/flash.$SUFFIX
cp $INSTDIR/$SQL.$SUFFIX $LIBDIR/sql.$SUFFIX

#
# Make sure the TERM is set
if [ -z "$TERMTYPE" -o $TERMTYPE = "dumb" ]
then
	while true
	do
		echo "Your TERM type is not set. Enter a terminal type:"
		echo
		if [ $IMP = "rs" ]
		then
			ls -C /usr/lib/terminfo/i
			echo
		fi
		echo -n "terminal type (q=quit) : "
		TERMTYPE="vt100"
		[ "$ASK" = "Y" ] && read TERMTYPE
		[ "$TERMTYPE" = "Q" ] && TERMTYPE="q"
		if [ "$TERMTYPE" = "q" ]
		then
			exit $ABANDON
		fi
		tset $TERMTYPE
		if [ $? -eq 0 ]
		then
			# Seems ok
			TERM=$TERMTYPE
			export TERM
			break
		fi
	done
fi

echo

# Set up diff. console type and char set.
# ---------------------------------------
if [ "$IMP" = "lx" ]; then                                    # [19]
	if [ "`consoletype`" = "vt" ]; then                       # [19]
		UNDOCON=1												# [19]
		unicode_stop											# [19]
		setfont lat0-sun16									# [19]
		OTERM=$TERM											# [19]
		export TERM=linux                              # [19]
	fi                                                        # [19]
	export LANG=en_US											#[22]
fi																# [19]
FSIINST=""
if [ -f $FSI.$SUFFIX ]; then
	FSIINST="-f"
fi
cd $INSTAL_PICK_DIR
./instal_pick $LIBDIR $FSIINST
RC=$?
if [ $RC != 0 ]
then
	exit $RC
fi

if [ "$UNDOCON" = "1" ]; then                             # [19]
	export TERM=${OTERM}                                  # [19]
	sh /etc/profile.d/lang.sh                                # [19]
fi                                                        # [19]

#
# Link the d3zip and d3unzip to the appropriate files
# ---------------------------------------------------
LinkZips

#
# Move the abs and dataset packages to their final destination & mk links
# -----------------------------------------------------------------------

# Remove original symlinks
rm -f /usr/lib/pick/dt
rm -f /usr/lib/pick/ab

# Move or copy ABS & DATAFILES
if [ "$DELETE" = 'y' ]
then
	mv $INSTDIR/$DAT.$SUFFIX /usr/lib/pick
	mv $INSTDIR/$ABS.$SUFFIX /usr/lib/pick
	[ -f $INSTDIR/$FSI.$SUFFIX ] && mv $INSTDIR/$FSI.$SUFFIX /usr/lib/pick
else
	cp $INSTDIR/$DAT.$SUFFIX /usr/lib/pick
	cp $INSTDIR/$ABS.$SUFFIX /usr/lib/pick
	[ -f $INSTDIR/$FSI.$SUFFIX ] && cp $INSTDIR/$FSI.$SUFFIX /usr/lib/pick
fi

# Make symlink
ln -s /usr/lib/pick/$DAT.$SUFFIX /usr/lib/pick/dt
ln -s /usr/lib/pick/$ABS.$SUFFIX /usr/lib/pick/ab

if [ "$DELETE" = 'y' ]
then
	for FILE in $FILES $ABS.$SUFFIX $DAT.$SUFFIX $FLA.$SUFFIX $INS.$SUFFIX $MON.$SUFFIX $SQL.$SUFFIX $ATI.SUFFIX $FSI.SUFFIX
	do
		rm -f $INSTDIR/$FILE
	done
	echo "D3 distribution files deleted."
fi

if [ $IMP = "uw" ]
then
 echo
 echo
 echo To complete the installation you must reboot your computer.
 echo -n "Would you like to reboot your computer now? "
 REBOOT=n
 [ "$ASK" = "Y" ] && read REBOOT
 [ "$REBOOT" = "Y" ] && REBOOT=y
 if [ "$REBOOT" != "y" ]
 then
 echo exit
 exit 1
 fi
 echo shutdown and reboot...
 cd /
 shutdown -y -g0 -i6
fi
