#!/bin/bash

. `dirname $0`/D3_setup_sub

######################################################################
# 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)) }'`
}


# 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
UNDOCON=0
# Check to make sure I can find all of my files
FILES="D3_ssn D3_setup D3_setup_mv D3_copyright D3_ugf"

# Setup the implementation specific variables
Initialize

GETPID=`GetPid`
if [ "$GETPID" != "" ]
then
	echo
	echo There may be some d3 processes running:
	echo
	GetPid
	echo
	DoEcho -n "Do you want to continue with the installation (Type y<return> to continue)? "
	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 ### < STILL NEEDS MERGE WORK FROM HERE DOWN

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

# 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

# Check to make sure I can find all of my files
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
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"
DoEcho -n "routine is finished with them? "
DELETE=n
[ "$ASK" = "Y" ] && read DELETE
[ "$DELETE" = "Y" ] && DELETE=y

echo
DoEcho -n "When the install completes, the distribution files will "
[ "$DELETE" != "y" ] && DoEcho -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
DoEcho -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

Finish

# 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

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
		DoEcho -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

cd $INSTAL_PICK_DIR
./instal_pick $LIBDIR
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
else
	cp $INSTDIR/$DAT.$SUFFIX /usr/lib/pick
	cp $INSTDIR/$ABS.$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
	do
		rm -f $INSTDIR/$FILE
	done
	echo "D3 distribution files deleted."
fi
