#!/bin/bash

#syntax: /bin/bash emcli_install -p moshelldir=/path/to/moshell,java=/path/to/java,perl=/path/to/perl
#the zipfiles moshell3ppbin.zip and moshell4emcli.zip must be in the same folder as the script emcli_install

moshellinstalldir=`dirname "$0"`
if [[ $moshellinstalldir != /* ]] ; then moshellinstalldir=`pwd`/$moshellinstalldir ; fi
#the emcli_install script works only when it is stored inside the same directory containing the files 
cd $moshellinstalldir

moshell_version=24.0j
exitcode=0
globmoshellrc=default
unamea=$(uname -a)
unr=0

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 checkPath()
{
	if [ ! -s $1 ] ; then  echo "!!! Warning: file $1 not found !!!" ; 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%%,*}
	for installoption in "$moshelldir" "$java" "$perl" ; do
		if [[ $installoption = *=* ]] ; then 
			echo "Invalid syntax: emcli_install -p moshelldir=xxx,java=yyy,perl=zzz"
			exitcode=1
			exit 
		fi
	done
	if [[ $installprefix = *=* ]] ; then installprefix="" ; fi
	if [[ $globmoshellrc = *=* ]] ; then globmoshellrc="default" ; fi
	echo "moshelldir = " $moshelldir
	echo "java = " $java
	echo "perl =" $perl
	#exit;
}

echo "#########################################"
echo "Installation of EMCLI for 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 
   #    echo "Cygwin 64-bit is currently not supported. Please install 32bit cygwin."
   #    exitcode=1
   #    exit
   #fi
   #must have cygwin 3.1.7 or higher (uname -r)
   #3.1.7(0.340/5/3)
   cygwinversion=`uname -r`
   #if [[ $cygwinversion = 1.* || $cygwinversion = 2.* || $cygwinversion = 3.0.* ||  $cygwinversion = 3.1.[0-6]\(* ]] ; 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.1.7 or higher) by rerunning the setup.exe from www.cygwin.com/setup-x86.exe"
	#exitcode=1
	#exit
   #fi
fi

binkeep=0
vobsinstall=0
noprompts=0
amos=0
while getopts "p:" options
do
case $options in
p) noprompts=1 ; installsettings=$OPTARG;;
esac
done

if [[ $noprompts = 1 ]] ; then read_installsettings 
else 
	echo "Invalid syntax: emcli_install -p moshelldir=xxx,java=yyy,perl=zzz"
	exitcode=1
	exit
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
trap 'exit $exitcode ' 0 1 2 3 15
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

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=`grep 'moshell_version=.*[0-9]' $old_moshellfile`
           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=`grep 'moshell_version=.*[0-9]' $old_moshellfile`
            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 emcli_install from inside the moshell directory." ; echo "Please go to a different directory and try again running emcli_install . " ; exitcode=1 ; exit ; fi
#echo $moshelldir
#echo $old_moshelldir
echo ""


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

echo ""
#cd $moshelltardir
if [[ -r moshell3ppbin.zip && -r moshell4emcli.zip ]] ; then : 
else
	echo "Cannot find moshell3ppbin.zip and/or moshell4emcli.zip"
	exitcode=1
	exit
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 ""
echo ""
echo "Unzipping moshell3ppbin.zip and moshell4emcli.zip ...."
echo "cd $moshelldir"
cd $moshelldir
unzip -o ${moshelltardir}/moshell3ppbin.zip
if [[ $? -eq 1 ]] ; then echo "Failed to unzip. Exiting..." ; exitcode=1 ; exit ; fi
unzip -o ${moshelltardir}/moshell4emcli.zip
if [[ $? -eq 1 ]] ; then echo "Failed to unzip. 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
	          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
	 	  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/jarxml ] ; then
echo ""
echo "Copying old jar/xml files to $moshelldir/moshell/jarxml directory..."
cp -r $old_moshelldir/jarxml $moshelldir/moshell

#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


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

#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/commonjars/scripts/*.pl ; do 
if test -f $file ; then 
if ! [[ $file = $moshelldir/gawk* || $file = $moshelldir/*.awk || $file = $moshelldir/README|| $file = $moshelldir/*.pdf ]] ; then
echo $file
$moshelldir/gawk -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" ' 
  /^emcli=0$/ { new_path="emcli=1"; replace=1}
  #/^comcli=0$/ { new_path="comcli=1"; replace=1}
  /^bash=/             {new_path=sprintf("bash=\"%s\"",bash)            ; replace=1} 
  /^#!.*\/bin\/bash/   {new_path=sprintf("#!%s",bash)                   ; replace=1}
  /^#!.*\/bin\/perl/   {new_path=sprintf("#!%s",perl)                   ; replace=1}
  /^java=/             {new_path=sprintf("java=\"%s\"",javaprog)        ; replace=1}   
  /^perl=/             {new_path=sprintf("perl=\"%s\"",perl)            ; replace=1}   
 /^inactivity_timeout=[1-9][0-9]+$/ { new_path="inactivity_timeout=600" ; replace=1}
 (replace==1)       {$0=gensub($1,new_path,"g",$0)                    ; 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       

#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)
#####################
echo "Setting all permissions on jarxml and parts of commonjars directory...."
chmod -R 777 $moshelldir/jarxml
chmod 755 $moshelldir/commonjars
chmod -R 777 $moshelldir/sitefiles
if [[ -d $moshelldir/cmdfiles ]] ; then chmod -R 777 $moshelldir/cmdfiles ; 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
chmod 666 ${moshelltardir}/moshell.tar 2>/dev/null


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 "
fi
