#
# SCCSID ("@(#)install.sh	1.36 07/09/18")
#

LibNameBuild=""
if [ -s "LibName.sh" ]
then
	. ./LibName.sh		# Define "LibNameBuild" for AS/400
else
	LibNameBuild="Opd34Exec"
fi

RemoveTempDir()
{
	$Dbg
	if [ $WrkDir = 1 ]; then cd ..; fi
	if [ ! -s $Tfile ]; then VarRestore=""; fi
	if [ ! -z "$VarRestore" ]
	then
		echo "Restoring input file..."
		$VarRestore -f $Tfile 2>>$Elog
		VarRestore=""
	fi
	if [ ! -z "$TmpDir" ]; then
		rm -rf $TmpDir
	fi
	if [ ! $Elog = "/dev/null" ]
	then
		if [ ! -s $Elog ]
		then
			rm -f $Elog
		fi
	fi
}

LogMesg()
{
	if [ ! $Elog = "/dev/null" ]
	then
		echo $* >>$Elog
	fi
}

Fatal()
{
	echo "$prg: server components cannot run (installation process aborted)"
	RemoveTempDir
	exit 9
}

prg=`basename $0 2>/dev/null`
TarFile=""
TmpDir=""
VarRestore=""

Dbg=":"
if [ ! -z "$LS_DEBUG" ]; then Dbg="set -x"; fi
$Dbg
StopOld=0
Error=0
Pnr=""
Exec=""
Force=0
WrkDir=0
while [ ! $# = 0 ]
do
	if [ "$1" = "-run" ]; then
		Exec="-x"
		StopOld=1
		shift 1
		continue
	fi
	if [ "$1" = "-f" ]; then
		Force=1
		shift 1
		continue
	fi
	if [ ! -z "$TarFile" ]; then
		Error=1
		break
	fi
	TarFile=$1; shift
done

if [ -z "$TarFile" ]; then
	TarFile=`ls *Point*.tar.Z 2>/dev/null`
	if [ -z "$TarFile" ]; then
		TarFile=`ls *Point*.tar.gz 2>/dev/null`
	fi
	if [ -z "$TarFile" ]; then
		TarFile=`ls *.tar.Z 2>/dev/null`
	fi
	if [ -z "$TarFile" ]; then
		TarFile=`ls *.tar.gz 2>/dev/null`
	fi
	if [ -z "$TarFile" ]; then
		TarFile=`ls *.tar 2>/dev/null`
	fi
	if [ -z "$TarFile" ]; then
		Error=1
	fi
	if [ $Error = 0 ]; then
		Nfiles=`ls $TarFile 2>/dev/null | wc -l | sed -e "/ /s///g" -e "s/	//g"`
		if [ ! $Nfiles = 1 ]; then
			Error=1
		fi
	fi
fi
if [ $Error = 1 ]; then
	echo "Usage: $prg <Tar-file>"
	exit
fi
PWD=`pwd 2>/dev/null`
startdir="$PWD"

LsTrace=""
Elog=/dev/null
if [ ! -z "$LS_LOG" ]
then	Elog=$LS_LOG
	case $Elog in
	/*)	;;
	*/*)	Elog=`basename $Elog 2>/dev/null`;Elog=$startdir/$Elog;;
	*)	Elog=$startdir/$Elog;;
	esac
	rm -f $Elog 2>/dev/null
	echo "Logging during installation activated" >$Elog
	LsTrace="-tT$Elog"
fi

case "$TarFile" in
[/\\]* | [a-z]:[/\\]*)	;;
*)	TarFile="$startdir/$TarFile";;
esac
if [ ! -w "$startdir" ]
then echo "$prg: current directory is not writable; please start again in a writable directory"
	Fatal
fi

Platform()
{
	$Dbg
	t1=""
	case $1 in
	ai*|AI*)		t1="aix";;
	OS/390)			t1="s390";;
	OS400)			t1="as400";;
	de*|DE*|osf*|OSF*)	t1="dec";;
	hp*|HP*)		t1="hpu";;
	sc*|SC*)		t1="sco";;
	se*|SE*|DY*)		t1="sequent";;
	sn*|SN*|SI*)		t1="sni";;
	su*|SU*|Su*)		t1="sun";;
	*)			t1="undefined";;
	esac
	echo $t1
}

OS400Installer()		# Arg 1: SAVF file with installer
{
	$Dbg
	if [ ! -s $1 ]; then return; fi
	if [ -z "$OPD_LIBNAME" ]
	then
		echo "Specify name of system library [max. 10 characters].\nTo use default value $LibName, press <ENTER> \c"
		read tem
		if [ ! -z "$tem" ]
		then
			LibName="$tem"
		fi
	fi
	TmpFile=InstProg-$$.txt
	ls /qsys.lib/$LibName.lib >$TmpFile 2>/dev/null
	if [ -s $TmpFile ]
	then
		echo "System library $LibName does already exist.\nExisting files will be overwritten.\nPlease confirm [y/n] \c"
		read tem
		StopNow=1
		case "$tem" in
		y*|Y*)	StopNow=0;;
		esac
		if [ $StopNow = 1 ]; then Fatal; fi
		ls /qsys.lib/$LibName.lib/OPD_INST.FILE >$TmpFile 2>/dev/null
		if [ -s $TmpFile ]
		then
			system -n "dltf file($LibName/opd_inst)"
		fi
		ls /qsys.lib/$LibName.lib/INSTALLER.PGM >$TmpFile 2>/dev/null
		if [ -s $TmpFile ]
		then
			system -n "DLTPGM PGM($LibName/INSTALLER)"
		fi
	else
		system -n "crtlib lib($LibName) aut(*change) crtaut(*change)"
		ls /qsys.lib/$LibName.lib >$TmpFile 2>/dev/null
		if [ -s $TmpFile ]; then echo "Failed to create system library $LibName."; Fatal; fi
	fi
	rm -f $TmpFile
	system -n "crtsavf file($LibName/opd_inst)"
	echo "Copy savefile into library..."
	cp $1 /QSYS.LIB/$LibName.LIB/OPD_INST.FILE
	InstRes=`system "dspsavf file($LibName/opd_inst)" | fgrep PGM`
	if [ -z "$InstRes" ]
	then
		echo "Copy savefile $1 into library $LibName failed"
		if [ ! -z "$JOBNAME" ]
		then
			system -n "DSPJOBLOG JOB($JOBNAME)" >$startdir/joblog.txt
			echo "View file $startdir/joblog.txt for more details"
		fi
		Fatal
	fi
	SaveLib=`system "dspsavf file($LibName/opd_inst)" 2>/dev/null | fgrep -i release | sed -e "s/:/XYZ:/" -e "s/.*XYZ:  *//" -e "s/  *.*//"`
	if [ -z "$SaveLib" ]
	then
		SaveLib="$LibNameBuild"
	fi
	echo "Restore installer program..."
	system -n "rstobj obj(*ALL) savlib($SaveLib) rstlib($LibName) dev(*SAVF) SAVF($LibName/opd_inst) option(*all)"
	ln -s /QSYS.LIB/$LibName.LIB/INSTALLER.PGM installer
	system -n "dltf file($LibName/opd_inst)"
	rm -f $1
}

CheckRestorePermission()
{
	$Dbg
	TmpInit=InitPerm-$$
	system rstobj 2>$TmpInit.txt
	TmpPerm=`fgrep CPD0032 $TmpInit.txt /dev/null`
	rm -f $TmpInit.txt
	StopNow=1
	if [ -z "$TmpPerm" ]
	then
		StopNow=0
	else
		if [ $1 = 1 ]
		then
			echo "Restoring programs from savefile most likely doesn't work."
			echo "Check if the current user has *SAVSYS special authority."
			echo "Do you want to proceed (y/Y)? \c"
			read tem
			case "$tem" in
			y*|Y*)	StopNow=0;;
			esac
		fi
	fi
	if [ $StopNow = 1 ]
	then
		echo "$prg: unable to restore objects from savefile."
		Fatal
	fi
}

CheckTar()
{
	$Dbg
	if [ ! -s $TmpTar ]; then return; fi
	if [ ! $Elog = "/dev/null" ]
	then
		LogMesg "Content of $TmpTar [error messages of tar]:"
		cat $1 >>$Elog
	fi
	sed -e "/Error exit delayed from previous errors/d" -e "/bytes from -/d" $1 >TarError.txt
	if [ -s TarError.txt ]; then
		TarError=`sed -e "/PAX: /d" -e "/pax: /d" -e "/config.txt/d" -e "/version.txt/d" -e "/command.txt/d" -e "/ls_ctl/d" -e "/installer/d" -e "/disclaim.txt/d" TarError.txt`
		if [ -z "$TarError" ]
		then
			LogMesg "Non fatal tar error message(s)."
			rm -f $1
			return
		else if [ "$TarError" = "tar: Exiting with failure status due to previous errors" ]
		then
			LogMesg "Non fatal tar error message(s)."
			rm -f $1
			return
		fi
		fi
		if [ ! $Elog = "/dev/null" ]
		then
			echo "++ start of logged messages:"
			cat $Elog
			echo "++ end   of logged messages."
		else
			cat $1
		fi
		echo "$prg: could not extract mandatory files from $TarFile (TarError: '$TarError')"
		echo "$prg: check if $TarFile was FTP-ed in ASCII mode (BINARY is necessary)"
		rm -f $1
		Fatal
	fi
	LogMesg "Non fatal tar error message(s)."
	rm -f $1
}

LibName="$OPD_LIBNAME"
if [ -z "$LibName" ]; then LibName="$LibNameBuild"; fi
Trg=`uname 2>>$Elog`
Pltf=`Platform $Trg`
Tfile=""
if [ $Trg = "OS400" ]
then
	CheckRestorePermission $Force
	case $TarFile in
	*.Z)	Tfile=${TarFile%".Z"};;
	*.z)	Tfile=${TarFile%".z"};;
	*.gz)	Tfile=${TarFile%".gz"};;
	*)	Tfile=$TarFile;;
	esac
else
	LibName=""
	LibNameBuild=""
fi

if [ -z "$Tfile" ]
then
	case $TarFile in
	*.Z)	Tfile=`echo $TarFile | sed -e "s/\.Z$//" 2>>$Elog`;;
	*.z)	Tfile=`echo $TarFile | sed -e "s/\.z$//" 2>>$Elog`;;
	*.gz)	Tfile=`echo $TarFile | sed -e "s/\.gz$//" 2>>$Elog`;;
	*)	Tfile=$TarFile;;
	esac
fi
if [ $Tfile = $TarFile ]
then
	if [ ! -s $TarFile ]
	then
		for i in "Z" "z" "gz"
		do
			if [ -s $TarFile.$i ]
			then
				TarFile=$TarFile.$i
				break
			fi
		done
	fi
fi
LogMesg "TarFile = $TarFile; Tfile = $Tfile"
if [ ! -s $TarFile ]
then
	if [ ! -s $Tfile ]
	then
		echo "$prg: $TarFile not found or empty"
		exit
	fi
	TarFile=$Tfile
fi
isTarFile=0
if [ -s $Tfile ]
then
	Ustar=`od -to1 -j257 -N6 $Tfile 2>/dev/null | sed -e "1!d" -e "s/.*  //" -e "s/ *//g"`
	case "$Ustar" in
	165163164141162000)	isTarFile=1;;
	0*165163164141162000)	isTarFile=1;;
	esac
	LogMesg "Check tar format of file $Tfile: $isTarFile [Ustar = $Ustar]"
fi

TmpDir="InstTemp.$$"
mkdir $TmpDir 2>>$Elog
Rval=$?
if [ ! $Rval = 0 ]; then
	TmpDir=""
	echo "$prg: could not make temporary directory"
	Fatal
fi
cd $TmpDir
WrkDir=1

ExecFiles="installer ls_ctl"
if [ $Trg = "OS400" ]
then
	ExecFiles="opd_installer.savf"	# Don't process "ls_ctl" (for now)
fi

Efiles="config.txt disclaim.txt version.txt command.txt $ExecFiles"
Cflag="-c"
TmpTar=tarext$$.txt
if [ $isTarFile = 0 ]
then
	# Check compression method
	value=`od -to1 -N2 $TarFile 2>/dev/null | sed -e "1!d" -e "s/.*  //" -e "s/ //g"`
	Cmd="undefined"
	case "$value" in
	37213)		Cmd="gzcat"; Cflag="-z"; VarRestore="gzip";;
	0*37213)	Cmd="gzcat"; Cflag="-z"; VarRestore="gzip";;
	37235)		Cmd="zcat"; Cflag=""; VarRestore="compress";;
	0*37235)	Cmd="zcat"; Cflag=""; VarRestore="compress";;
	*)	echo "$prg: unable to determine compression method of $TarFile"
		echo "$prg: please uncompress file $TarFile manually and use the uncompressed file"
		Fatal
		;;
	esac
	LogMesg "Compression style of file $TarFile: $Cmd [first bytes: $value]"
	if [ $Trg = "OS400" ]
	then
		LogMesg "Uncompress via '$VarRestore -d $TarFile'"
		echo "Uncompressing input file..."
		$VarRestore -df $Tfile
		if [ ! -s $Tfile ]
		then
			VarRestore=""
			LogMesg "Failed to uncompress $TarFile"
			Fatal
		fi
		isTarFile=1
		Cflag="-f$VarRestore"
	else
		VarRestore=""
		if [ "$Cmd" = "gzcat" ]; then
			case $PATH in
			:*)	PATH=:$startdir$PATH;;
			*)	PATH=$startdir:$PATH;;
			esac
			_xyz=`type gzcat 2>/dev/null`
			rv=$?
			if [ -z "$_xyz" ]; then rv=3; fi
			if [ ! $rv = 0 ]
			then
				_xyz=`type gzip 2>/dev/null`
				rv=$?
				if [ -z "$_xyz" ]; then rv=4; fi
				if [ ! $rv = 0 ]
				then
					echo "Program gzip/gzcat not found: cannot extract files, installation aborted"
					LogMesg "Program gzip/gzcat not found: cannot extract files, installation aborted"
					RemoveTempDir
					exit 8
				fi
				Cmd="gzip -cdq"
			fi
			Tfile=$TarFile
		fi
		echo "Extracting initial files from $TarFile..."
		LogMesg "Extracting initial files via command:"
		LogMesg "\t$Cmd $Tfile | tar xf - $Efiles 2>>$TmpTar"
		$Cmd $Tfile | tar xf - $Efiles 2>>$TmpTar
		CheckTar $TmpTar
	fi
fi
if [ $isTarFile = 1 ]; then
	echo "Extracting installer from $TarFile..."
	LogMesg "Extracting installer via command:"
	if [ $Trg = "OS400" ]
	then
		LogMesg "\tpax -r -pp -C037 -f $Tfile -n $Efiles"
		pax -r -pp -C037 -f $Tfile -n $Efiles 2>$TmpTar
	else
		LogMesg "\ttar xf $Tfile $Efiles"
		tar xf $Tfile $Efiles 2>$TmpTar
	fi
	CheckTar $TmpTar
	TarFile=$Tfile
fi
if [ $Trg = "OS400" ]
then
	OS400Installer opd_installer.savf 2>>$Elog
fi

Ptmp=""
Pwrk=`sed -e "/SRV_PortNr/!d" -e "/	/s///g" -e "/ /s///g" -e "/SRV_PortNr=/s///" config.txt /dev/null 2>/dev/null`
if [ ! -z "$Pwrk" ]; then
	for i in $Pwrk
	do
		case $i in
		[0-9]*)	Ptmp=$i
			break;;
		*)	;;
		esac
		if [ ! -z "$Ptmp" ]; then break; fi
	done
fi
WrkDir=0
cd ..

# Determine: first install or upgrade
Upgrade=0
if [ -s $TmpDir/command.txt ]; then
	Upgrade=1
	StopOld=1
fi

# Check presence of disclaimer file
Udir="-d $TmpDir"
Dfil="$TmpDir/disclaim.txt"
if [ ! -s $Dfil ]; then
	if [ ! $Elog = "/dev/null" ]
	then
		LogMesg "File $Dfil not seen"
		ls -l $TmpDir >>$Elog
	fi
	Dfil="disclaim.txt"
	if [ ! -s $Dfil ]; then
		echo "$prg: disclaimer file missing"
		Fatal
	fi
fi

# Check presence of installer program (first in tar file or otherwise in current directory)
Iprg=""
if [ $Upgrade = 0 ]
then
	Iprg=`ls $TmpDir/installer 2>>$Elog`
	if [ -z "$Iprg" ]; then
		echo "$prg: installer program not found"
		echo "$prg: server components are not installed"
		Fatal
	fi
	if [ ! -z "$Ptmp" ]
	then
		Pnr="-p"$Ptmp
	fi
else
	Iprg=`ls installer 2>>$Elog`
	if [ -s $TmpDir/installer ]
	then
		Iprg=`ls $TmpDir/installer 2>>$Elog`
		if [ -z "$Iprg" ]; then
			if [ ! $Elog = "/dev/null" ]
			then
				LogMesg "File $Iprg not seen"
				ls -l $TmpDir >>$Elog
			fi
		fi
	fi
fi
if [ -z "$Iprg" ]; then
	echo "$prg: installer program not found"
	echo "$prg: server components are not updated"
	Fatal
fi

Error=0
if [ $StopOld = 1 ]; then
	# Check presence of control program
	Cprg=`ls $TmpDir/ls_ctl 2>>$Elog`
	if [ -z "$Cprg" ]; then
		Cprg=`ls ls_ctl 2>>$Elog`
	fi
	if [ -z "$Cprg" ]; then
		echo "Control program missing (cannot stop already running server components)"
	else
		chmod 555 $Cprg 2>>$Elog
		RmvCnf=""
		ln $TmpDir/config.txt . 2>>$Elog
		if [ $? = 0 ]; then
			RmvCnf="config.txt"
		fi
		$Cprg $Pnr -st0 -c stopall
		Rval=$?
		if [ ! -z "$RmvCnf" ]; then
			rm -f $RmvCnf
		fi
		if [ ! $Rval = 0 ]; then
			if [ -s config.txt ]; then
				echo "Failed to kill a running version of the listener program (installation aborted)"
				Error=1
			fi
		fi
	fi
fi

if [ $Error = 0 ]; then
	chmod 555 $Iprg 2>>$Elog
	trap 'RemoveTempDir' ERR
	LogMesg "Activating installer program:"
	SysLibrary=""
	if [ ! -z "$LibName" ]; then SysLibrary="-l$LibName"; fi
	LogMesg "$Iprg -u$Upgrade $Cflag $Udir $Exec $Pnr $LsTrace $SysLibrary $TarFile $Pltf"
	PATH=$PATH:..
	export PATH
	$Iprg -u$Upgrade $Cflag $Udir $Exec $Pnr $LsTrace $SysLibrary $TarFile $Pltf
	Error=$?
	VarRestore=""
	trap - ERR
	if [ ! $Error = 0 ]; then
		Exec="No"
	fi
	if [ -z "$Exec" ]; then
		PortMsg=0
		if [ $Upgrade = 0 ]; then
			if [ -z "$Pnr" ]; then PortMsg=1; fi
		fi
		if [ $PortMsg = 1 ]; then
			echo "Port numbers in file config.txt still can be adjusted when server components are not running."
			echo "Use command \"./installer -P <other port number>\" (in the installation directory)"
		fi
		echo "Server components can be started via command \"./server.sh -start\" (in the installation directory)"
	fi
fi
RemoveTempDir
exit $Error
