#!/bin/bash

##################################################################################################
#  moshell_install 4.1 2013-07-30
#  Finn Magnusson, finn.magnusson@ericsson.com
#  
#  INSTRUCTION:
#  This script is for installing moshell.
#  Download the file moshellxxx.zip file from http://utran01.epa.ericsson.se/moshell
#  and place it in a directory of your choice (eg: your home directory)
#  Go to that directory (eg: cd /home/userid):
#  Unzip the archive:
#   >> unzip -o moshellxxx.zip
#  Run the "moshell_install" script with command:
#   >> bash moshell_install
#
#  Follow the prompts:
#       1- enter directory where moshell should be installed:
#  ->If you already had a previous version of moshell, install the new one in the SAME location as the old one.
#  This way, your old jar-, xml-, site- files will get copied to the new moshell directory.
#  The old moshell directory will be renamed to moshell_<today's date and time>.
#  ->If you didn't have a previous version of moshell, the jarxml and ior directory will be empty and will be fetched
#  automatically from the node the first time you run moshell.
#       2- enter pathes to java and perl.
#
#  Once all the pathes have been defined, moshell.tgz is deflated into the moshell directory and all pathes are set 
#  in the various files.
#
#  Note: to make an installation that will work both on solaris and linux (from a common mounted drive), 
#        run moshell_install with the option "-vk", from the solaris machine. E.g. bash moshell_install -vk 
#  Note: to avoid the prompts, it is also possible to run: 
#         bash moshell_install -p moshelldir=/path/to/moshell/folder,java=/path/to/java,perl=/path/to/perl[,installprefix=/installation/prefix][,globmoshellrc=/path/to/globmoshellrc][,unr=<0|1|2|3>][,labsettings=<0|1>]
#	  the options installprefix and globmoshellrc are optional. 
#             - installprefix is for ITK installations. 
#             - globmoshellrc can be used to set a different path for the globmoshellrc file (by default it is in moshell/jarxml/moshellrc)
# Note: to avoid the prompts it is also possible to run:
#         bash moshell_install -m moshelldir=/path/to/moshell/folder[,java=/path/to/java][,perl=/path/to/perl][,installprefix=/installation/prefix][,globmoshellrc=/path/to/globmoshellrc][,unr=<0|1|2|3>][,labsettings=<0|1>]
#         this is the same as option -p but the java and perl path are optional
##################################################################################################

moshellinstalldir=`dirname "$0"`
if [[ $moshellinstalldir != /* ]] ; then moshellinstalldir=`pwd`/$moshellinstalldir ; fi
#the script works only when we are inside the directory containing the moshell_install and moshell.tgz
cd $moshellinstalldir

moshell_version=22.0v
exitcode=0
globmoshellrc=default
unamea=$(uname -a)

case "$unamea" in
	[Ll][iI][Nn][uU][xX]*)  
		os=linux
		if [[ $unamea = *x86_64* ]] ; then os=lin64 ; fi
		;;
	SunOS*sparc*) 
		os=solaris
		;;
	[cC][yY][gG]*)
		os=exe
		;; 
	SunOS*) 
		os=sol86
		;;
esac


function ask_for_pathes()
{   
	if [[ $noprompts -ge 1 ]] ; then
		java=$(which java | grep java)
		javaprog=$java
		perl=$(which perl | grep perl)
		echo "Path to Java = $java"
		echo "Path to Perl = $perl"
		checkPath $java
		checkPath $perl
		return
	fi
	#####################
	# Path to Java
	#####################
	java=$(which java | grep java)
	javaversion=$($java -version 2>&1)
	if [[ "$javaversion" > 'java version "1.2.2' ]] ; then
	read -e -p "    - Path to Java = $java . OK ? [y/n] "
	            case $REPLY in
	              n*|N*) read -e -p "Please enter path to java (must be 1.2.2 or higher): " java              	     
	              	     checkPath $java
	                     ;;
	              *) ;;
	            esac
	else 
		read -e -p "Please enter path to Java (must be 1.2.2 or higher): " java              	     
	        checkPath $java	
	fi	
	#copy java into javaprog for later use
	javaprog=$java       

	#####################
	# Path to perl
	#####################
	echo ""
	perl=$(which perl | grep perl)
	case $perl in
	  /*perl) read -e -p "    - Path to perl (used by mobatch) = $perl . OK ? [y/n] "
	            case $REPLY in
	              n*|N*) read -e -p "Please enter path to perl: " perl
	                     checkPath $perl
	                     ;;
	              *) ;;
	            esac
	            ;;
	  *) read -e -p "Please enter path to perl: " perl
	     checkPath $perl
	     ;;     
	esac
	
}

function checkPath()
{
	if [ ! -s $1 ] ; then  echo "!!! Warning: file $1 not found !!!" ; fi
}

function make_limited_checks()
{
	tmpline1="Checking if encrypted partition /moshellroot is present..." ; result1="NO"
	tmpline2="Checking if directory /home/moshell is present..." ; result2="NO"
	tmpline3='Checking if we are logged in as user "moshell"...' ; result3="NO"
	tmpline4="Checking we are running linux or solaris..."       ; result4="NO"
	if [[ -d /moshellroot ]] ; then result1="OK" ; fi
	if [[ -d /home/moshell ]] ; then result2="OK" ; fi
	if [[ `whoami` = moshell ]] ; then result3="OK" ; fi
	if [[ $unamea != CYG* ]]  ; then result4="OK" ; fi
	echo ""
	echo "$tmpline1 $result1"
	echo "$tmpline2 $result2"
	echo "$tmpline3 $result3"
	echo "$tmpline4 $result4"
	echo ""
	if [[ $result1 = NO || $result2 = NO || $result3 = NO || $result4 = NO ]] ; then echo "One or more conditions are not met. Exiting..." ;  exitcode=1 ; exit ; fi
}
function prompt_for_install_type_and_moshelldir()
{
	#####################
	# Type of installation
	#####################
	echo ""
	echo "Please choose the type of installation. "
	echo "    0) Full Version"
	echo "    1) Restricted+"
	echo "    2) Restricted"
	echo "    3) Limited"
	read -e -p "Your Choice (0, 1, 2, or 3): " unr
	case $unr in 
	 0|1|2) ;;
	 3) make_limited_checks ;;
	 *) echo "Invalid choice." ; exitcode=1 ; exit ;;
	esac
	
	#####################
	# Path to moshelldir
	#####################
	#case1: enter /home/eric/tools/moshell and moshell exists
	#case2: enter /home/eric/tools/moshell and moshell doesn't exist
	#case3: enter /home/eric/tools         and there is an moshell in /home/eric/tools
	#case4: enter /home/eric/tools         and there is no moshell in /home/eric/tools
	#case5: enter /home/eric/tools         and tools doesn't exist  
	#case6: enter /home/eric/tools/moshell and tools/moshell doesn't exist
	
	#if moshelldir finishes by moshell (e.g. /home/eric/tools/moshell)
	#     -if moshelldir exists mv moshell then unpack (case 1)
	#     -if moshelldir doesn't exist, just unpack (case 2)
	#if moshelldir doesn't finish by moshell (.e.g. /home/eric/tools)
	#     -if there is an moshell dir in moshelldir,  mv it and unpack (case 3)
	#     -if there is no moshell dir in moshelldir, just unpack (case 4)
	#(     -if moshelldir doesn't exist, create it, then unpack (case 5)---> not covered)
		
	echo "Please enter the following absolute pathes (auto-completion using <TAB>):"
	echo ""
	case $unr in 
	0|1|2) read -e -p "    - Directory where moshell should be installed: " moshelldir ;;
	3) moshelldir="/moshellroot" ;;
	esac
}

function reuse_old_pathes()
{
	if [[ -f $old_moshellfile && -r $old_moshellfile && -r $(dirname $old_moshellfile)/mobatch ]] ; then
		if [[ $noprompts = 0 ]] ; then
			read -e -p "There is already an moshell in that directory. Do you want to reuse the same java/perl pathes? [y/n] "
			echo ""
		else REPLY="y"
		fi
		case $REPLY in 
		    y*|Y*) #use $0 instead of $1 since the java path can be made of several words, eg: c:/program files/...
			   java=$(eval echo $(awk '/^java=/{split($0,a,"=");print a[2] ;exit}' $old_moshellfile)) ; javaprog=$java  ; echo "Java=$javaprog"
		           perl=$(eval echo $(awk '/^#!/{print substr($1,3);exit}' $(dirname $old_moshellfile)/mobatch))  ; echo "Perl=$perl"
		           ;;
		    n*|N*) ask_for_pathes
		           ;;
		esac
	else 
		ask_for_pathes
	fi
}
function read_installsettings()
{
	moshelldir=${installsettings/*moshelldir=} ; moshelldir=${moshelldir%%,*}
	java=${installsettings/*java=} ; java=${java%%,*} ; javaprog=$java
	perl=${installsettings/*perl=} ; perl=${perl%%,*}
	unr=${installsettings/*unr=} ; 	unr=${unr%%,*}
	labsettings=${installsettings/*labsettings=} ; 	labsettings=${labsettings%%,*}
	installprefix=${installsettings/*installprefix=} ; installprefix=${installprefix%%,*}
	globmoshellrc=${installsettings/*globmoshellrc=} ; globmoshellrc=${globmoshellrc%%,*}
	for installoption in "$moshelldir" "$java" "$perl" ; do
		if [[ $installoption = *=* && $noprompts = 1 ]] ; then 
			echo "Invalid syntax: moshell_install -p moshelldir=xxx,java=yyy,perl=zzz"
			exitcode=1
			exit 
		fi
	done
	if [[ $unr = *=* ]] ; then unr=0 ; fi
	if [[ $installprefix = *=* ]] ; then installprefix="" ; fi
	if [[ $globmoshellrc = *=* ]] ; then globmoshellrc="default" ; fi
	echo "moshelldir = " $moshelldir
	echo "java = " $java
	echo "perl =" $perl
	echo "unr = "$unr
	echo "installprefix = " $installprefix
	echo "globmoshellrc = " $globmoshellrc
	echo "labsettings = " $labsettings
	#exit;
}

echo "#########################################"
echo "Installation of Moshell $moshell_version"
echo "#########################################"
echo ""
if [[ $unamea = [cC][yY][gG]* ]] ; then 
   #only 32 bit supported at the moment
   cygarch=`arch`
   if [[ $cygarch = *x86_64* ]] ; then :
   else
       echo "Cygwin 32-bit is not supported anymore. Please install 64bit cygwin."
	  read -e -p "Install on 32-bit cygwin anyway? [y/n] "
	            case $REPLY in
	              n*|N*)        exitcode=1 ; exit
	                     ;;
	              *) ;;
	            esac
   fi
   #must have cygwin 3.3.4 or higher (uname -r)
   #3.3.4(0.341/5/3)
   cygwinversion=`uname -r`
   #if [[ $cygwinversion = 1.* || $cygwinversion = 2.* || $cygwinversion = 3.0.* ||  $cygwinversion = 3.1.* ||  $cygwinversion = 3.2.* ||  $cygwinversion = 3.3.[0-3]\(* ]] ; then
	#echo "!!! Your cygwin installation is out of date and incompatible with the latest moshell version !!! "
	#echo "Please upgrade to the latest cygwin version (3.3.4 or higher) by rerunning the setup.exe from www.cygwin.com/setup-x86.exe"
	#exitcode=1
	#exit
   #fi
fi

if [[ $BASH_VERSINFO -lt 2 ]] ; then echo "!!! Warning: bash version is too old. Please use a newer version of bash (at least 2.x)" ; exitcode=1 ; exit ; fi

binkeep=0
vobsinstall=0
noprompts=0
amos=0
while getopts "kvap:m:" options
do
case $options in
k) binkeep=1 ;;
v) vobsinstall=1 ;;
p) noprompts=1 ; installsettings=$OPTARG;;
a) amos=1 ; unr=0 ; noprompts=1 ; moshelldir=/opt/ericsson/amos ; java=/usr/bin/java ; javaprog=$java ; perl=/usr/bin/perl ;;
m) noprompts=2 ; installsettings=$OPTARG;;
esac
done

if [[ $noprompts -ge 1 && $amos = 0 ]] ; then read_installsettings ; fi

#if [[ $binkeep = 1 && $vobsinstall = 1 && $unamea != SunOS*sparc* ]] ; then 
#	echo "Error: moshell_install -vk must be run from a Solaris/sparc machine!"
#	exitcode=1
#	exit
#fi

if [[ $amos = 1 ]] ; then
	if [[ ! -d /opt/ericsson/amos || ! -d /var/opt/ericsson/amos ]] ; then
		echo "Error: amos folder is missing. Exiting..."
		exitcode=1
		exit
	fi
fi

moshelltardir=$(pwd)
#cd /

#####################
# Path to tempdir 
# set readline options
# set $PATH
#####################
if [ -d /tmp ] ; then  tempdir=/tmp
elif [ -d /var/tmp ] ; then tempdir=/var/tmp
fi
tempinputrc=$tempdir/input$$
trap 'rm -f $tempinputrc ; exit $exitcode ' 0 1 2 3 15
echo -n -e "set show-all-if-ambiguous on\nset mark-directories on\nset visible-stats on\nset expand-tilde on\n" > $tempinputrc 2>/dev/null
if test -f $tempinputrc ; then INPUTRC=$tempinputrc ; fi
export PATH=$PATH:/usr/bin:/bin:/usr/local/bin:/sbin:/usr/sbin:/opt/sfw/bin:/usr/ucb      #/usr/ucb is needed for whoami 
echo ""
bash=$BASH

#GNU bash, version 2.03.0(1)-release (sparc-sun-solaris)
#GNU bash, version 2.05b.0(1)-release (i686-pc-cygwin)
#GNU bash, version 2.05b.0(1)-release (i586-mandrake-linux-gnu)
#GNU bash, version 2.05b.0(1)-release (i386-redhat-linux-gnu)
#GNU bash, version 3.00.0(2)-release (sparc-sun-solaris2.8)
	

if [[ $noprompts = 0 ]] ; then 
	prompt_for_install_type_and_moshelldir 
	if [[ $moshelldir = */opt/ericsson/amos* ]] ; then 
		echo "Error: AMOS installation must be performed with option -a, ie: moshell_install -a"
		exitcode=1 ; exit 
	fi
fi

# If an installation prefix was provided, add it now. But remember original path
# This is needed when rpm packaging is done because rpm uses a temporary build root
targetmoshelldir=moshelldir
if [[ "$installprefix" ]]; then moshelldir=$installprefix$moshelldir ; fi

old_moshelldir=""
old_moshellfile=""
old_moshellversion=""
#convert ~ to full path name
moshelldir=$(eval echo $moshelldir)
#convert relative path to full path
case $moshelldir in
/*) ;;
*) moshelldir=$(pwd)/$moshelldir ;;
esac
#remove any / at the end of moshelldir and 
case $(dirname $moshelldir) in 
/) ;; 
*) moshelldir=$(dirname $moshelldir)/$(basename $moshelldir) ;;
esac
#echo $moshelldir

case $moshelldir in 
  */moshell|moshell|moshell/|*/moshell/)
       if [ -d $moshelldir ] ; then
           #echo "case 1"
           old_moshellfile=$moshelldir/moshell
           old_moshellversion=`(strings $old_moshellfile | grep 'moshell_version=.*[0-9]') 2>/dev/null`
           old_moshellversion=${old_moshellversion#*_version=\"}
           old_moshellversion=${old_moshellversion%\"*}
           old_moshellversion=${old_moshellversion// /}           
           old_moshelldir=${moshelldir}_${old_moshellversion}_`date +%y%m%d_%H%M`
       elif ! [ -d $moshelldir/.. ] ; then  #case6
           echo "This directory doesn't exist. Creating it..."
           if ! mkdir -p $(dirname $moshelldir) ; then echo "Could not create $moshelldir. Exiting..." ; exitcode=1 ; exit ; fi
       fi
       #case 2: do nothing
       #remove the moshell part in the directory name:
       moshelldir=`dirname $moshelldir`       
       ;;
  *)   if [ -d ${moshelldir}/moshell ] ; then
            #echo "case 3"
            moshelldir=${moshelldir}/moshell
            old_moshellfile=$moshelldir/moshell
            old_moshellversion=`(strings $old_moshellfile | grep 'moshell_version=.*[0-9]') 2>/dev/null`
            old_moshellversion=${old_moshellversion#*_version=\"}
            old_moshellversion=${old_moshellversion%\"*}
            old_moshellversion=${old_moshellversion// /}            
            old_moshelldir=${moshelldir}_${old_moshellversion}_`date +%y%m%d_%H%M`
            moshelldir=`dirname $moshelldir`
       fi
       #case 4: do nothing
       if ! [ -d $moshelldir ] ; then #case5
            echo "This directory doesn't exist. Creating it..."
            if ! mkdir -p $moshelldir ; then echo "Could not create $moshelldir. Exiting..." ; exitcode=1 ; exit ; fi
       fi
       ;;
esac
#NOTE: moshelldir is in the form /home/eric/tools. When moshell.tgz is unpacked, the moshell dir is created
#Check that you have write permission in the moshelldir:
if ! test -w $moshelldir ; then echo "" ; echo "You do not have write permission in $moshelldir; Exiting...." ; exitcode=1 ; exit ; fi
if [[ $(pwd) = $moshelldir/moshell ]] ; then echo ""; echo "It is not supported to run moshell_install from inside the moshell directory." ; echo "Please go to a different directory and try again running moshell_install . " ; exitcode=1 ; exit ; fi
#echo $moshelldir
#echo $old_moshelldir
echo ""


if [[ $noprompts != 1 ]] ; then reuse_old_pathes ; fi


#####################
# Path to moshell.tgz
#####################                     
#case 1: 
#case 2:
#case 3:

echo ""
#cd $moshelltardir
if [ -f moshell.tgz ] ; then :  
elif [ -f moshell.tar ] ; then untared=yes
else 
  #cd /
  read -e -p "Enter path to moshell.tgz or moshell.tar: " moshelltardir
  #Convert moshelltardir to full path
  case $moshelltardir in
  /*) ;;
  *) moshelltardir=$(pwd)/$moshelltardir ;;
  esac
  case $moshelltardir in
  */moshell.t[ga][zr]) moshelltardir=`dirname $moshelltardir` ; cd $moshelltardir ;;
  *) cd $moshelltardir  ;;
  esac  
  if [ -f moshell.tgz ] ; then : 
  elif [ -f moshell.tar ]  ; then untared=yes 
  else echo "Can't find moshell.tgz or moshell.tar! Exiting..." ; exitcode=1 ; exit ; 
  fi
fi


#####################
# Installation
#####################                     
if [[ $old_moshelldir != "" ]] ; then
	echo "Moving old moshell directory to $old_moshelldir..."
	if mv $moshelldir/moshell $old_moshelldir ; then
	   echo "Moshell will be installed in $moshelldir"
	else echo "Renaming of old moshell directory failed. Exiting..." ; exitcode=1 ; exit
	fi
fi

echo ""
echo "Starting Installation...."
echo ""
if [[ $untared != "yes" ]] ; then
echo "Unzipping moshell.tgz...."
if [[ $amos -eq 1 ]] ; then cp -f moshell.tgz moshell.tgz.bak ; fi
gzip -df moshell.tgz
if [[ $? -eq 1 ]] ; then exitcode=1 ; exit ; fi
if [[ $amos -eq 1 ]] ; then mv -f moshell.tgz.bak moshell.tgz ; fi
fi
echo ""
echo "Untaring moshell.tar...."
cd $moshelldir
tar xvf ${moshelltardir}/moshell.tar
if [[ $? -eq 1 ]] ; then echo "Failed to untar. Exiting..." ; exitcode=1 ; exit ; fi

chmod -R 755 $moshelldir/moshell
echo ""
cd $moshelldir/moshell
if [[ $binkeep != 1 ]] ; then
	case "$unamea" in
	 [Ll][iI][Nn][uU][xX]*)  
	          echo "Installing binary files for Linux..."
	          #for file in *.linux ; do mv $file ${file%.linux} ; done
	          #for file in commonjars/*.linux ; do mv $file ${file%.linux} ; done
	          #for file in commonjars/bin/*.linux ; do mv $file ${file%.linux} ; done
	          rm -f *.exe commonjars/*.exe
	          rm -f commonjars/lib/*.so.solaris commonjars/lib/*.dll commonjars/lib/*.so.sol86
	          if [[ $unamea = *x86_64* ]] ; then mv gawk.lin64 gawk ; fi
	          ;;
	 SunOS*sparc*) 
	          echo "Installing binary files for Solaris/sparc..."
	          for file in *.solaris ; do mv $file ${file%.solaris} ; done
	          for file in commonjars/*.solaris ; do mv $file ${file%.solaris} ; done
	          for file in commonjars/bin/*.solaris ; do mv $file ${file%.solaris} ; done
	 	  rm -f gawk.lin64 commonjars/*.lin64
	          rm -f *.exe commonjars/*.exe 
	          rm -f commonjars/lib/*.so.linux commonjars/lib/*.dll commonjars/lib/*.so.sol86
	          ;;
	 [cC][yY][gG]*)
	 	  echo "Installing binary files for Cygwin..."
	 	  rm -f gawk.lin64 commonjars/*.lin64
	 	  rm -f commonjars/lib/*.so.linux commonjars/lib/*.so.solaris commonjars/lib/*.so.sol86
	 	  ;; 
	 SunOS*) 
	          echo "Installing binary files for Solaris/x86..."
	          for file in *.sol86 ; do mv $file ${file%.sol86} ; done
	          for file in commonjars/*.sol86 ; do mv $file ${file%.sol86} ; done
	          #for file in commonjars/bin/*.sol86 ; do mv $file ${file%.sol86} ; done
	 	  rm -f gawk.lin64 commonjars/*.lin64
	          rm -f *.exe commonjars/*.exe 
	          rm -f commonjars/lib/*.so.linux commonjars/lib/*.dll commonjars/lib/*.so.solaris
	          ;;	 	  
	esac
	rm -f *.solaris commonjars/*.solaris *.linux commonjars/*.linux *.sol86 commonjars/*.sol86
else
	:
#	case "$unamea" in
#	 [Ll][iI][Nn][uU][xX]*)  
#	          echo "Installing binary files for Linux..."
#	          for file in *.linux ; do ln -s $moshelldir/moshell/$file ${file%.linux} ; done
#	          for file in commonjars/*.linux ; do ln -s $moshelldir/moshell/$file ${file%.linux} ; done
#	          ;;
#	 SunOS*sparc*) 
#	          echo "Installing binary files for Solaris/sparc..."
#	          for file in *.solaris ; do ln -s $moshelldir/moshell/$file ${file%.solaris} ; done
#	          for file in commonjars/*.solaris ; do ln -s $moshelldir/moshell/$file ${file%.solaris} ; done
#	          ;;
#	 *[cC][yY][gG]*)
#	 	  echo "Installing binary files for Cygwin..."
#	 	  ;;          
#	 SunOS*) 
#	          echo "Installing binary files for Solaris/x86..."
#	          for file in *.sol86 ; do ln -s $moshelldir/moshell/$file ${file%.sol86} ; done
#	          for file in commonjars/*.sol86 ; do ln -s $moshelldir/moshell/$file ${file%.sol86} ; done
#	          ;;
#	esac
fi
#####################
# Copy old ior,jar and xml files to new moshell
#####################   
#echo $old_moshelldir
if [ -d $old_moshelldir/sitefiles ] ; then
echo ""
echo "Copying old sitefiles to $moshelldir/moshell/sitefiles directory..."
cp -r $old_moshelldir/sitefiles $moshelldir/moshell
#Changing permissions:
chmod -R 755 $moshelldir/moshell/sitefiles
fi

if [ -d $old_moshelldir/iorfiles ] ; then
echo ""
echo "Copying old iorfiles to $moshelldir/moshell/iorfiles directory..."
cp -r $old_moshelldir/iorfiles $moshelldir/moshell
#Changing permissions:
chmod -R 777 $moshelldir/moshell/iorfiles
fi

if [ -d $old_moshelldir/cmdfiles ] ; then
echo ""
echo "Copying old cmdfiles to $moshelldir/moshell/cmdfiles directory..."
cp -r $old_moshelldir/cmdfiles $moshelldir/moshell
#Changing permissions:
chmod -R 755 $moshelldir/moshell/cmdfiles
fi

if [ -d $old_moshelldir/compfiles ] ; then
echo ""
echo "Copying old compfiles to $moshelldir/moshell/compfiles directory..."
cp -r $old_moshelldir/compfiles $moshelldir/moshell
#Changing permissions:
chmod -R 755 $moshelldir/moshell/compfiles
fi

if [ -d $old_moshelldir/jarxml ] ; then
echo ""
echo "Copying old jar/xml files to $moshelldir/moshell/jarxml directory..."
cp -r $old_moshelldir/jarxml $moshelldir/moshell
if [ -r $old_moshelldir/commonjars/iaik_jce_full_us.jar ] ; then
	cp $old_moshelldir/commonjars/iaik_jce_full_us.jar $moshelldir/moshell/jarxml
fi
#Changing permissions:
chmod -R 777 $moshelldir/moshell/jarxml
echo "Compressing uncompressed MOM files ..."
for file in $moshelldir/moshell/jarxml/*.xml $moshelldir/moshell/jarxml/*.cache ; do
if [[ -f "$file" ]] ; then gzip -f $file ; chmod 666 $file.gz ; fi
done
fi


if [ -r $old_moshelldir/commonjars/xalan.jar ] ; then 
echo ""
echo "Copying old momdoc jarfiles to $moshelldir/moshell/commonjars directory..."
cp $old_moshelldir/commonjars/xalan.jar $old_moshelldir/commonjars/xerces.jar $old_moshelldir/commonjars/bsf.jar $moshelldir/moshell/commonjars
fi

if [ -r $old_moshelldir/commonjars/host.p12 ] ; then 
echo ""
echo "Copying old security files to $moshelldir/moshell/commonjars directory..."
cp $old_moshelldir/commonjars/host.p12* $moshelldir/moshell/commonjars
if [ -r $old_moshelldir/commonjars/sam.pbe ] ; then cp $old_moshelldir/commonjars/sam.pbe* $moshelldir/moshell/commonjars ; fi
fi


#####################
# Set pathes in Script files
#####################
#change moshelldir to finish by moshell
moshelldir=$moshelldir/moshell
#change path to perl to finish by perl (in case the user just gave the directory of perl)
if [[ "$perl" != *perl* ]] ; then perl=$perl/perl ; fi
#if the installprefix was used then the path replacements must be made with targetmoshelldir, otherwise use moshelldir
if [[ "$installprefix" ]] ; then targetmoshelldir=$targetmoshelldir ; else targetmoshelldir=$moshelldir ; fi

#Set the LD_LIBRARY_PATH so gawk may find some missing libraries
if [[ $unamea = [Ll][iI][nN][uU][xX]*x86_64* ]] ; then gawklib="lin64"   
elif [[ $unamea = [Ll][iI][nN][uU][xX]* ]]      ; then gawklib="linux"   
elif [[ $unamea = SunOS*sparc* ]]               ; then gawklib="solaris" 
elif [[ $unamea = SunOS* ]]                     ; then gawklib="sol86"   
else gawklib="cygwin" 
fi
export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:$moshelldir/commonjars/lib/${gawklib} 


echo ""
echo "Setting Pathes in script files..."
for file in $moshelldir/commonjars/*.sh $moshelldir/* $moshelldir/examples/perl_api/UpgTool.pl $moshelldir/commonjars/pmSummary/bin/pmSummary.pl $moshelldir/commonjars/scripts/*.pl $moshelldir/commonjars/ste/wrapper.pl $moshelldir/commonjars/pm/gnuplot/*.pl $moshelldir/commonjars/*.pl ; do 
if test -f $file ; then 
if ! [[ $file = $moshelldir/gawk* || $file = $moshelldir/monitor* || $file = $moshelldir/zpm* || $file = $moshelldir/*.pdf || $file = $moshelldir/*.awk ]] ; then
echo $file
gawkpath=$moshelldir/gawk
if [[ $binkeep = 1 ]] ; then gawkpath=$moshelldir/gawk.$os ; fi
if [[ $os = lin64 || $cygarch = *x86_64* ]] ; then : 
else gawkpath=gawk ; fi
$gawkpath -v moshelldir="$targetmoshelldir" -v bash="$bash" -v tempdir="$tempdir" -v perl="$perl" -v javaprog="$javaprog" -v unr="$unr" -v vobsinstall="$vobsinstall" -v amos="$amos" -v globmoshellrc="$globmoshellrc" -v thefile="$file" -v labsettings="$labsettings" --source ' 
BEGIN{ 
	if (moshelldir ~ /^(\/vobs\/iov\/rnc\/bin|\/afs\/.sunrise.ericsson.se\/app\/moshell)/) labsettings=1
}
  /^jarxmldir=/ && amos==1 { sub(/.moshelldir/,"/var/opt/ericsson/amos"); replace=0}
  /^decoder=.vobs.iov.rnc.bin.decoder.pl/ && amos==1 { sub(/=.*$/,"=/opt/ericsson/amos/decoder/decoder.pl") ; replace=0}
  /^polu_confirmupgrade=1/ && amos==1 { sub(/=.*$/,"=0") ; replace=0}
  vobsinstall==1 && /^vobsinstallation=/ { new_path="vobsinstallation=1"; replace=1}
  labsettings==1 && thefile~/moshell$/ && /^restart_confirmation=/ { new_path="restart_confirmation=0" ; replace=1}
  labsettings==1 && thefile~/moshell$/ && /^use_complete_mom=/ { new_path="use_complete_mom=1" ; replace=1}
  labsettings==1 && thefile~/moshell$/ && /^exclude_preliminary=/ { new_path="exclude_preliminary=0" ; replace=1}
  labsettings==1 && thefile~/moshell$/ && /^use_babel2=/ { new_path="use_babel2=1" ; replace=1}
  labsettings==1 && thefile~/moshell$/ && /^use_nodelete=/ { new_path="use_nodelete=0" ; replace=1}
  labsettings==1 && thefile~/moshell$/ && /^dcg_name_utc=/ { new_path="dcg_name_utc=1" ; replace=1}
  labsettings==1 && thefile~/moshell$/ && /^ip_database=/ { new_path="ip_database=$sitefiledir/ipdatabase,/proj/caotLabLog/tools/moshell_ipdatabase" ; replace=5}
  labsettings==1 && thefile~/moshell$/ && /^umask 000/ { new_path="umask 002" ; replace=5}
  /^bash=/             {new_path=sprintf("bash=\"%s\"",bash)            ; replace=1} 
  /^#!.*\/bin\/bash/   {new_path=sprintf("#!%s",bash)                   ; replace=1}
  /^#!.*\/bin\/perl/   {if (moshelldir ~ /^(\/vobs\/iov\/rnc\/bin|\/afs\/.sunrise.ericsson.se\/app\/moshell)/ && thefile~/mobatch$/) new_path="#!/usr/bin/env perl"
                        else new_path=sprintf("#!%s",perl)                   ; replace=1}
  /^java=/             {new_path=sprintf("java=\"%s\"",javaprog)        ; replace=1}   
  /^perl=/             {if (moshelldir ~ /^(\/vobs\/iov\/rnc\/bin|\/afs\/.sunrise.ericsson.se\/app\/moshell)/) new_path=sprintf("perl=\"%s\"","/app/moshell/bin/perl")
  			else new_path=sprintf("perl=\"%s\"",perl)       ; replace=1}   
  /^globmoshellrc=/ && globmoshellrc != "default" && $1!~/\$globmoshellrc/ { $0="globmoshellrc="globmoshellrc ; replace=0}
  /^unr=0/             {$0="unr="unr                                    ; replace=0}
  /^gawk=.L/ && unr==3 {sub(/\$moshelldir/,"/moshellroot/commonjars") ; sub(/\/.gawkprog/,"/gwrap")  ; replace=0} 
  /^my ..moshelldir. = / && unr==3 {$0="my $moshelldir = \"/moshellroot\";" ; replace=0}
  /^(jarxmldir|commonjardir|sitefiledir)=/ && unr==3 {sub(/\$moshelldir/,"/moshellroot") ; replace=0} 
 (replace==1)       {$0=gensub($1,new_path,"g",$0)                    ; replace=0}
 (replace==3)       {$0=gensub($3,new_path,"g",$0)                    ; replace=0}
 (replace==4)       {$0=gensub($4,new_path,"g",$0)                    ; replace=0}
 (replace==5)       {$0=new_path                                      ; replace=0}
 		    {print}
 ' $file  > ${file}.temp
   if test $? -eq 0 ; then 
       mv ${file}.temp $file
       chmod 755 $file
   else 
       echo "Failed. Exiting..." ; exitcode=1 ; exit
   fi  
fi
fi
done       

#Do this at the end so that it is a soft link and not a file, otherwise "set pathes" will make it a file.
ln -s mobatch mobatch.pl
ln -s moshell monode
#For lttng-relayd and babeltrace who were compiled with link to libz.so instead of libz.so.1
#cd commonjars/lib/lin64
#ln -s libz.so.1 libz.so
#cd -
#cd commonjars/lib/linux
#ln -s libz.so.1 libz.so
#cd -

#####################
# Setting permissions (555 on Scripts, 777 on subdirectories, 444 on host.p12)
# But not for AMOS : CR OSS-134434
#####################
if [[ $amos != 1 ]] ; then
	echo "Setting all permissions on jarxml and parts of commonjars directory...."
	chmod -R 777 $moshelldir/jarxml
	chmod 755 $moshelldir/commonjars
	chmod -R 777 $moshelldir/commonjars/pm $moshelldir/commonjars/scripts
	chmod -R 777 $moshelldir/sitefiles
	if [[ -d $moshelldir/cmdfiles ]] ; then chmod -R 777 $moshelldir/cmdfiles ; fi
fi

#echo "Removing cached MOM files ...."
#rm $moshelldir/jarxml/*.cache 2>/dev/null

#chmod -R 755 $moshelldir
#chmod -R 777 $moshelldir/cmdfiles $moshelldir/sitefiles $moshelldir/logfiles $moshelldir/iorfiles $moshelldir/jarxml $moshelldir/compfiles $moshelldir/examples 
#chmod 444 $moshelldir/commonjars/host.p12
#chmod 777 $moshelldir/moshell

#####################
# Adaptations for restricted version
#####################
if [[ $unr = 0 ]] ; then
   rm -r $moshelldir/commonjars/bin
elif [[ $unr = 1 ]] ; then
   echo "Adaptations for RESTRICTED+ version...."
   if [[ $unamea = SunOS*sparc* ]] ; then 
   	$moshelldir/commonjars/zip -P Ericss0n $moshelldir/other.zip $moshelldir/other.awk
   else 
   	zip -P Ericss0n $moshelldir/other.zip $moshelldir/other.awk
   fi
   rm $moshelldir/other.awk
   rm -r $moshelldir/commonjars/src $moshelldir/commonjars/bin
elif [[ $unr = 2 ]] ; then 
   echo "Adaptations for RESTRICTED version...."
   rm $moshelldir/other.awk
   rm -r $moshelldir/commonjars/src $moshelldir/commonjars/bin
elif [[ $unr = 3 ]] ; then 
   echo "Adaptations for LIMITED version...."
   rm $moshelldir/other.awk
   rm -r $moshelldir/commonjars/src
   cp $moshelldir/gawk $moshelldir/commonjars
   chmod 711 $moshelldir/commonjars/bin/*
   chmod u+s $moshelldir/commonjars/bin/*
   if [[ -d /moshellroot/commonjars && -d $old_moshelldir ]] ; then mv /moshellroot/commonjars /moshellroot/bin /moshellroot/examples $old_moshelldir ; fi
   mv $moshelldir/commonjars/bin /moshellroot
   mv $moshelldir/commonjars $moshelldir/examples /moshellroot
   mv /moshellroot/bin/pm* /moshellroot/bin/gwrap /moshellroot/commonjars
   if [[ ! -d /moshellroot/jarxml ]] ; then mv $moshelldir/cmdfiles $moshelldir/sitefiles $moshelldir/jarxml /moshellroot ;fi
   chmod 700 $moshelldir
   mv $moshelldir/mobatch /moshellroot/bin/mobatch
   #problem with pmXtab and -pipe:
   	cp $moshelldir/pmXtab /moshellroot/commonjars
   	chmod 755 /moshellroot/commonjars/pmXtab
   #copy moshell/mobatch /moshellroot/bin
   #copy moshell/restartcollector /moshellroot/bin
fi

cat <<EOF

Installation Successful!
You can now run moshell from the directory ${moshelldir}.

###########################################################################
# Check your variable settings in the moshell file                        #
# (eg path to java, ipdatabase, corba credentials, etc)                   #
# Alternatively, these variables can be set in ~/.moshellrc to avoid them #
# being reset after each moshell installation                             #
###########################################################################

EOF
rm -f $tempinputrc 
chmod 666 ${moshelltardir}/moshell.tar 2>/dev/null

if [[ $unr > 0 ]] ; then
   echo "Removing installation files..."
   rm $moshelltardir/moshell.tar
   rm $moshelltardir/moshell${moshell_version}.zip
   rm $moshelltardir/moshell_install
fi
if [[ $unr = 3 ]] ; then
   echo "Setting permissions in /home/moshell..."
   echo "chmod 755 /home/moshell"
   chmod 755 /home/moshell
   echo "chmod -R 777 /home/moshell/moshell_logfiles"
   chmod -R 777 /home/moshell/moshell_logfiles
fi
if [[ $amos = 1 ]] ; then
   if [[ ! -d /var/opt/ericsson/amos/jarxml ]] ; then mv $moshelldir/jarxml /var/opt/ericsson/amos ; fi
   if [[ ! -r /var/opt/ericsson/amos/jarxml/moshellrc ]] ; then cp $moshelldir/jarxml/moshellrc /var/opt/ericsson/amos/jarxml ; fi
   #username=$USER does not need to be set in jarxml/moshellrc anymore
   if [[ `grep -c '^username=\$USER' /var/opt/ericsson/amos/jarxml/moshellrc` > 0 ]] ; then 
       grep -v '^username=\$USER' /var/opt/ericsson/amos/jarxml/moshellrc > /var/opt/ericsson/amos/jarxml/moshellrc.temporarybuffer
       mv /var/opt/ericsson/amos/jarxml/moshellrc.temporarybuffer /var/opt/ericsson/amos/jarxml/moshellrc
   fi
   mkdir -p /var/opt/ericsson/amos/moshell_logfiles
   for file in $moshelldir/* ; do
       if [[ -f $file ]] ; then chmod 555 $file ; fi
   done
   #ENM
   if [[ $unamea = [Ll][iI][nN][uU][xX]* ]] ; then 
       mkdir -p /ericsson/log/amos/moshell_logfiles
       chmod 1777 /ericsson/log/amos
       chmod 777 /ericsson/log/amos/moshell_logfiles
   else
       #TR HU22533 (http://jira-nam.lmera.ericsson.se/browse/OSS-94606)
       mkdir -p /var/opt/ericsson/log/AMOS
       chmod 777 /var/opt/ericsson/log/AMOS
   fi
   #TR HN61080
   chmod -t /var/opt/ericsson/amos/jarxml
   #TR HM92378 
   chmod +t /opt/ericsson/amos/moshell/sitefiles
   chmod +t /opt/ericsson/amos/moshell/commonjars/pm
   chmod +t /opt/ericsson/amos/moshell/commonjars/scripts
   chmod +t /opt/ericsson/amos/moshell/commonjars/scripts/ombat
   #TR HT24359: the two commands below take too long
   #chmod -R 777  /var/opt/ericsson/amos 2>/dev/null
   #TR HL96864 
   #find /var/opt/ericsson/amos -type d -exec chmod +t '{}' \;
   #TR HT40953
   chmod 777 /var/opt/ericsson/amos/moshell_logfiles
   #TR HV38787
   chmod -R 777 /var/opt/ericsson/amos/jarxml
fi

if [[ $os = lin64 || $cygarch = *x86_64* ]] ; then : 
else
	echo "The binary files for this platform are not stored in the moshell package. To complete the installation please store the file http://newtran01.au.ao.ericsson.se/moshell/downloads/moshellbins.zip inside the moshell folder and run: cd /path/to/moshell && unzip -o /path/to/moshellbins.zip && chmod -R 755 /path/to/moshell"
fi

