#!/bin/bash
# SCENARI app installer script
# LICENCE[[
# Version: MPL 1.1/GPL 2.0/LGPL 2.1/CeCILL 2.O
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is kelis.fr code.
#
# The Initial Developer of the Original Code is
# samuel.monsarrat@kelis.fr
#
# Portions created by the Initial Developer are Copyright (C) 2006-2008
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
#
#
# Alternatively, the contents of this file may be used under the terms of
# either of the GNU General Public License Version 2 or later (the "GPL"),
# or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# or the CeCILL Licence Version 2.0 (http://www.cecill.info/licences.en.html),
# in which case the provisions of the GPL, the LGPL or the CeCILL are applicable
# instead of those above. If you wish to allow use of your version of this file
# only under the terms of either the GPL, the LGPL or the CeCILL, and not to allow
# others to use your version of this file under the terms of the MPL, indicate
# your decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL, the LGPL or the CeCILL. If you do not
# delete the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL, the LGPL or the CeCILL.
# ]]LICENCE

# Init variables
appName="SCENARIclient"
appNameFull="SCENARIclient 3.5"
appVersion="3.5"
appVersionFull="3.5.202"
appPublisher="SCENARI"
appClientName="scChain"
appDescription="Se connecter à un SCENARIserver fournissant des chaînes éditoriales créées avec SCENARIbuilder."
appPrefixDefaultRoot="/opt"
linkPrefixDefaultRoot="/usr"
appPrefixDefaultUser=$HOME
linkPrefixDefaultUser=$HOME
logFile="/tmp/"$appName$appVersionFull"-install_"$(date +%Y.%m.%d-%H.%M.%S)".log"
tmpDir="/tmp/scinstall"
ecoLine=""
forceMode="no"
appPath=""
locateExists=""

#==================================================
# Internal functions...
#==================================================

#_______________________________________________________________________________
# xFindOriginalFilePath : accepts a list of complete file paths as input.
# For eath input file path, resolve symlinks untill we find the real file, stop 
# and return the first real file that is found in the variable that was used as 
# input.
xFindOriginalFilePath () {
	vInputVarName=\$"$1"
	vInputVarVal=`eval "expr \"$vInputVarName\" "`
	if [ -z "$vInputVarVal" ];then
		return
	fi
	vOriginalPwd=`/bin/pwd`
	vFound="0"
	for vfilePath in $vInputVarVal; do
		while [ -h "$vfilePath" ]; do
			bn=`basename "$vfilePath"`
			cd `dirname "$vfilePath"`
			vfilePath=`/bin/ls -l "$bn" | sed -e 's/^.* -> //' `
			if [ -f "$vfilePath" ]; then
				break
			fi
		done
		if [ -f "$vfilePath" ]; then
			vFound="1"
			break				
		fi
	done
	cd "$vOriginalPwd"
	if [ "$vFound" = "1" ]; then
		eval "$1=$vfilePath"
	else
		eval "$1=''"
	fi
}

#_______________________________________________________________________________
# xAddXulrunnerPlugin : attempts to find .so and .xpt files passed as input.
# if found, add symlinks in /bin/xulrunner/plugins/
xAddXulrunnerPlugin () {

	vSoPath="/usr/lib/mozilla/plugins/$1.so
/usr/lib/browser-plugins/$1.so
/usr/lib/firefox/plugins/$1.so"
	xFindOriginalFilePath vSoPath
	if [ ! -f "$vSoPath" ] && [ "$locateExists" = "yes" ]; then
		vSoPath=`locate $1.so`
		xFindOriginalFilePath vSoPath
	fi
	if [ -f "$vSoPath" ]; then
		ln -s $vSoPath $appPath"/bin/xulrunner/plugins/"$1".so" >> $logFile 2>&1
		echo -n "Added xulrunner plugin to $appPath/bin/xulrunner/plugins: $1 (.so" >> $logFile

		vXptPath="/usr/lib/mozilla/plugins/$1.xpt
/usr/lib/browser-plugins/$1.xpt
/usr/lib/firefox/plugins/$1.xpt"
		xFindOriginalFilePath vXptPath
		if [ ! -f "$vXptPath" ] && [ "$locateExists" = "yes" ]; then
			vXptPath=`locate $1.xpt`
			xFindOriginalFilePath vXptPath
		fi
		if [ -f "$vXptPath" ]; then
			ln -s $vXptPath $appPath"/bin/xulrunner/plugins/"$1".xpt" >> $logFile 2>&1
			echo " and .xpt)" >> $logFile
		else
			echo " only)" >> $logFile
		fi
	fi
	echo -n "."
}

# Start...
if echo "$1" | grep -q h ; then
	echo
	echo "$appNameFull installer"
	echo
	echo "This script will install $appNameFull on your computer."
	echo "You can either run this script as root, in which case a system-wide" 
	echo "installation will be made and a menu entry can be added, or you can run"
  echo "this script as a normal user in which case $appNameFull will be installed"
  echo "in your home directory."
	echo
  echo "This installer has the following options:"
  echo "-h   prints this message and exits"
  echo "-f   'force' mode, the installer does not interact with the user, all"
  echo "     default choices are used. If the application is already installed"
  echo "     it will be replaced. This is basically equivalent to pressing return"
  echo "     for each question the the installer normally asks the user."
	echo
  echo "This installer script is Copyright (C) 2006-2008 samuel.monsarrat@kelis.fr"
  echo "Licensed under MPL 1.1/GPL 2.0/LGPL 2.1/CeCILL 2.O"
	echo
	exit 0
fi
if echo "$1" | grep -q f ; then
	forceMode="yes"
fi
if echo "$1" | grep -q l ; then
	lastScAppBinPathFile="$2"
else
	lastScAppBinPathFile=$tmpDir"/lastScAppBinPath.txt"
fi

locate --version >> /dev/null 2>&1
if [ "$?" -ne "0" ];then
	locateExists="no"
else
	locateExists="yes"
fi


echo "$appName$appVersionFull installer log" >> $logFile
echo "________________________________________________________________________________"
echo " "
echo "  Welcome to the $appNameFull installer"
if [ $forceMode = "yes" ]; then
echo "  Force mode activated: no user interaction, all default choices will be used."
fi
echo " "

# Check if the script is being run as root or as a simple user.
if [ `id -u` -ne "0" ]
then
	echo "  You do not have root access."
	echo "  $appNameFull will be installed in your home directory by default."
	installType="user"
	appPrefixDefault=$appPrefixDefaultUser
	linkPrefixDefault=$linkPrefixDefaultUser
else
	echo "  You have root access."
	echo "  $appNameFull will be installed system wide by default"
	installType="root"
	appPrefixDefault=$appPrefixDefaultRoot
	linkPrefixDefault=$linkPrefixDefaultRoot
fi
echo "________________________________________________________________________________"

# Display license.
if [ -f "license.txt" ] && [ $forceMode = "no" ] ; then 
	echo
	echo "Please read and accept the following end user license before"
	echo "installing $appNameFull."
	echo -n "Press Enter to continue"
	read userRes
	more license.txt
	echo
	echo -n "Do you agree to the above license terms? [yes/NO] "
	read userRes
	userRes=`echo $userRes | tr 'A-Z' 'a-z'`
	if [ "$userRes" != "y" ] && [ "$userRes" != "yes" ] ; then 
		echo "If you don't agree to the license you can't install $appNameFull."
		echo "Installation aborted, $appNameFull was not installed."
	  	exit 1
	fi
fi

# Look for OpenOffice.
vLocOO=""
if [ $locateExists = "yes" ] ; then 
	vLocOO=`locate soffice.bin`
	xFindOriginalFilePath vLocOO
fi
if [ -z "$vLocOO" ] ; then
	vLocOO="/opt/openoffice.org3/program/soffice.bin
/opt/openoffice.org2.4/program/soffice.bin
/opt/openoffice.org2.3/program/soffice.bin
/opt/openoffice.org2.2/program/soffice.bin
/opt/openoffice.org2.1/program/soffice.bin
/opt/openoffice.org2.0/program/soffice.bin
/usr/lib/openoffice/program/soffice.bin
/usr/lib/openoffice2/program/soffice.bin
/usr/lib/openoffice.org/program/soffice.bin
/usr/lib/openoffice.org3.0/program/soffice.bin
/usr/lib/openoffice.org2.4/program/soffice.bin
/usr/lib/openoffice.org2.3/program/soffice.bin
/usr/lib/openoffice.org2.2/program/soffice.bin
/usr/lib/openoffice.org2.1/program/soffice.bin
/usr/lib/openoffice.org2.0/program/soffice.bin
/usr/lib/ooo-3.0/program/soffice.bin
/usr/lib/ooo-2.4/program/soffice.bin
/usr/lib/ooo-2.3/program/soffice.bin
/usr/lib/ooo-2.2/program/soffice.bin
/usr/lib/ooo-2.1/program/soffice.bin
/usr/lib/ooo-2.0/program/soffice.bin"
	xFindOriginalFilePath vLocOO
fi
if [ -z "$vLocOO" ] ; then 
	echo
	echo "WARNING: The installer cannot find OpenOffice on this system."
	echo "Although OpenOffice is not mandatory in order to use $appNameFull,"
	echo "certain features may be affected if it is not present."
	echo "It is therefore advisable to install OpenOffice (http://www.openoffice.org)."
fi

appPathDefault=$appPrefixDefault"/"$appPublisher"/"$appName$appVersion
echo
if [ $forceMode = "no" ]; then
	# Prompt for install location.
	echo -n "Please give the installation location [$appPathDefault]: "
	read appPath
else
	echo "$appNameFull will be installed in $appPathDefault"
fi
if [ "$appPath" = "" ]; then
	appPath=$appPathDefault
fi

# Delete previous installation if folder exists
if [ -d $appPath ]; then
	if [ ! -w $appPath ]; then
		echo
		echo "You do not have write permission for $appPath."
		echo "Installation aborted, $appNameFull was not installed."
	  	exit 1
	fi
	if [ $forceMode = "no" ]; then
		echo
		echo "WARNING: $appPath. is not empty."
		echo "This folder will be deleted before proceding."
		echo -n "Do you want to continue? [Y/n]: "
		read userRes
		userRes=`echo $userRes | tr 'A-Z' 'a-z'`
	else
		echo "WARNING: $appPath. is not empty."
		echo "This folder will be deleted and replaced with $appNameFull."
		userRes="y"
	fi
	if [ "$userRes" = "n" ]; then 
		echo "Installation aborted, $appNameFull was not installed."
  		exit 1
	fi
	echo -n "Delete previous installation..." >> $logFile
	rm -Rf $appPath >> $logFile 2>&1
	echo "OK" >> $logFile
	echo
fi

mkdir -p $appPath
if [ ! -w $appPath ]; then
	echo "You do not have write permission for $appPath."
	echo "Installation aborted, $appNameFull was not installed."
  	exit 1
fi

#==============================================================================
# Unpack the application
#==============================================================================
#Unpack SCx to the right location in appPrefix
echo -n "Unpacking  $appNameFull..."
echo -n "Unpack $appNameFull to $appPath..." >> $logFile
mkdir -p $appPath >> $logFile 2>&1
tar -x -z --no-same-owner --no-same-permissions -f $appName".tar.gz"  -C $appPath >> $logFile 2>&1
#Unpack xulrunner...
tar -x -z --no-same-owner --no-same-permissions -f $appPath"/bin/xulrunner.tar.gz" -C $appPath"/bin/" >> $logFile 2>&1
rm -f $appPath"/bin/xulrunner.tar.gz" >> $logFile 2>&1
echo "OK"
echo "OK" >> $logFile
#Unpack and setup jre if it exists...
if [ -f $appPath"/bin/scServer/jre/jre.tar.gz" ]; then
	echo -n "Unpacking the embedded java runtime environment..."
	echo -n "Unpacking the embedded java runtime environment..." >> $logFile
	tar -x -z --no-same-owner --no-same-permissions -f $appPath"/bin/scServer/jre/jre.tar.gz" -C $appPath"/bin/scServer/jre/" >> $logFile 2>&1
	rm -f $appPath"/bin/scServer/jre/jre.tar.gz" >> $logFile 2>&1
	echo "OK"
	echo "OK" >> $logFile

	# Dump client classes...
	echo "Dump client classes:" >> $logFile
	$appPath/bin/scServer/jre/bin/java -client -Xshare:dump >> $logFile 2>&1
fi

#==============================================================================
# Setup the application
#==============================================================================
echo -n "Application setup..."

#Replace default xulrunner icon with app icon...
echo -n "Replace default xulrunner icon with app icon..." >> $logFile
rm -f $appPath"/bin/xulrunner/chrome/icons/default/default.xpm" >> $logFile 2>&1
cp $appPath"/bin/"$appClientName"/chrome/icons/default/scenaricms.xpm" $appPath"/bin/xulrunner/chrome/icons/default/default.xpm" >> $logFile 2>&1
echo "OK" >> $logFile

#Rename xulrunner executables with the actual application name...
echo -n "Rename xulrunner executables with the actual application name..." >> $logFile
mv $appPath"/bin/xulrunner/xulrunner" $appPath"/bin/xulrunner/"$appName >> $logFile 2>&1
mv $appPath"/bin/xulrunner/xulrunner-bin" $appPath"/bin/xulrunner/"$appName"-bin" >> $logFile 2>&1
echo "OK" >> $logFile

#Plugins...
#Make sure bundled plugins are executable before we start adding symlinks to external files...
if [ -d "$appPath/bin/xulrunner/plugins" ]; then
	chmod a+x $appPath/bin/xulrunner/plugins/*.so >> $logFile 2>&1
fi
#Link the java plugin to xulrunner (in order for applets to work in SCENARI)...
if [ -f "$appPath/bin/scServer/jre/plugin/i386/ns7/libjavaplugin_oji.so" ]; then
	ln -s $appPath"/bin/scServer/jre/plugin/i386/ns7/libjavaplugin_oji.so" $appPath"/bin/xulrunner/plugins/libjavaplugin_oji.so" >> $logFile 2>&1
	echo "Added xulrunner plugin to $appPath/bin/xulrunner/plugins: libjavaplugin_oji (java - .so only)" >> $logFile
fi
#Link the openoffice plugin to xulrunner (in order for OOo documents to preview in SCENARI)...
ooProgramPath=`dirname $vLocOO`
if [ -f "$ooProgramPath/libnpsoplugin.so" ]; then
	ln -s $ooProgramPath"/libnpsoplugin.so" $appPath"/bin/xulrunner/plugins/libnpsoplugin.so" >> $logFile 2>&1
	echo "Added xulrunner plugin to $appPath/bin/xulrunner/plugins: libnpsoplugin (openoffice - .so only)" >> $logFile
fi
#Link flashplayer plugin to xulrunner...
xAddXulrunnerPlugin "libflashplayer"
#Link totem plugins to xulrunner (in order for media (video, audio) documents to preview in SCENARI)...
xAddXulrunnerPlugin "libtotem-basic-plugin"
xAddXulrunnerPlugin "libtotem-complex-plugin"
xAddXulrunnerPlugin "libtotem-gmp-plugin"
xAddXulrunnerPlugin "libtotem-mully-plugin"
xAddXulrunnerPlugin "libtotem-narrowspace-plugin"
#Link mplayer plugins to xulrunner (in order for media (video, audio) documents to preview in SCENARI)...
xAddXulrunnerPlugin "mplayerplug-in"
xAddXulrunnerPlugin "mplayerplug-in-dvx"
xAddXulrunnerPlugin "mplayerplug-in-gmp"
xAddXulrunnerPlugin "mplayerplug-in-qt"
xAddXulrunnerPlugin "mplayerplug-in-rm"
xAddXulrunnerPlugin "mplayerplug-in-wmp"

#Replace ==appPath== in launcher script
echo -n "Set up launcher script..." >> $logFile
appPathEsc=$(echo $appPath | sed -e 's/\//\\\//g')
sed -e "s/==app.path==/$appPathEsc/g" < $appPath"/"$appName > $appPath"/"$appName".tmp"
rm -f $appPath"/"$appName >> $logFile 2>&1
mv $appPath"/"$appName".tmp" $appPath"/"$appName >> $logFile 2>&1

#Replace ==app.nameFull== in launcher script
sed -e "s/==app.nameSig==/$appName$appVersion/g" < $appPath"/"$appName > $appPath"/"$appName".tmp"
rm -f $appPath"/"$appName >> $logFile 2>&1
mv $appPath"/"$appName".tmp" $appPath"/"$appName >> $logFile 2>&1
echo "OK" >> $logFile

#Setup log file 
echo -n "Setup log file..." >> $logFile
touch "$appPath"/bin/scenari.log >> $logFile 2>&1
chmod a+w "$appPath"/bin/scenari.log >> $logFile 2>&1
echo "OK" >> $logFile

#Set user rights
echo -n "Set user rights (chmod a+x) on various elements..." >> $logFile
chmod a+x $appPath"/"$appName >> $logFile 2>&1
if [ -f "$appPath/bin/scServer/nativlib/lame" ]; then
	chmod a+x $appPath"/bin/scServer/nativlib/lame" >> $logFile 2>&1
fi
if [ -f "$appPath/bin/scServer/nativlib/sox" ]; then
	chmod a+x $appPath"/bin/scServer/nativlib/sox" >> $logFile 2>&1
fi
if [ -f "$appPath/bin/scServer/nativlib/soxmix" ]; then
	chmod a+x $appPath"/bin/scServer/nativlib/soxmix" >> $logFile 2>&1
fi
if [ -f "$appPath/bin/scServer/nativlib/im/convert" ]; then
	chmod a+x $appPath"/bin/scServer/nativlib/im/convert" >> $logFile 2>&1
fi
if [ -d "$appPath/bin/xulrunner/components" ]; then
	chmod a+x $appPath/bin/xulrunner/components/*.so >> $logFile 2>&1
fi
echo "OK" >> $logFile

#Leave a trace of the the installed launcher's path for possible automated wsppack installs
echo -n "Leave a trace of the the installed launcher's path in $lastScAppBinPathFile..." >> $logFile
mkdir -p `dirname $lastScAppBinPathFile` >> /dev/null 2>&1
echo "vLastScAppBinPath=$appPath/$appName" > $lastScAppBinPathFile
echo "OK" >> $logFile

echo "OK"
echo "$appNameFull has been installed in $appPath"

#==============================================================================
# Setup the enviroment
#==============================================================================
# Enviroment integration (links menus etc)
echo "Enviroment integration:" >> $logFile
echo
if [ $forceMode = "no" ]; then
	echo -n "Do you want to incorprate $appNameFull into your enviroment? [Y/n]: "
	read userRes
	userRes=`echo $userRes | tr 'A-Z' 'a-z'`
else
	userRes="y"
fi
if [ "$userRes" = "" ] || [ "$userRes" = "y" ] ; then 
	# Add links
	if [ "$installType" = "root" ] && [ $forceMode = "no" ]; then
		echo -n "Please specify the path prefix for your system [$linkPrefixDefault]: "
		read linkPrefix
		if [ "$linkPrefix" = "" ] ; then
			linkPrefix=$linkPrefixDefault
		fi
	else
		linkPrefix=$linkPrefixDefault 
	fi
	rm -f $linkPrefix"/bin/"$appName$appVersion >> $logFile 2>&1
	ln -s $appPath"/"$appName $linkPrefix"/bin/"$appName$appVersion >> $logFile 2>&1
	echo "The link $linkPrefix/bin/$appName$appVersion has been added"
	echo "The link $linkPrefix/bin/$appName$appVersion has been added" >> $logFile

	# Add menu item if possible (root and existing menu structure)...
	if [ "$installType" = "root" ] && [ -d $linkPrefix"/share/applications" ]; then
		appDesktopFilePath=$linkPrefix"/share/applications/"$appName$appVersion".desktop"
		echo "[Desktop Entry]" > $appDesktopFilePath
		echo "Name=$appNameFull" >> $appDesktopFilePath
		echo "Encoding=UTF-8" >> $appDesktopFilePath
		echo "Exec=$appName$appVersion" >> $appDesktopFilePath
		echo "Terminal=false" >> $appDesktopFilePath
		echo "StartupNotify=true" >> $appDesktopFilePath
		echo "Icon=$appPath/bin/$appClientName/chrome/icons/default/scenaricms.png" >> $appDesktopFilePath
		echo "Type=Application" >> $appDesktopFilePath
		echo "Categories=Office;" >> $appDesktopFilePath
		echo "Comment=$appDescription" >> $appDesktopFilePath
		chmod 644 $appDesktopFilePath  >> $logFile 2>&1

		echo "$appNameFull has been added to the Office sub-menu of "
		echo "the Applications menu."
		echo "The file $appDesktopFilePath has been created" >> $logFile
	fi
else
	echo "$appNameFull has not been incorporated into your enviroment"
fi
echo
echo "$appNameFull installation finished"
echo "$appNameFull installation finished" >> $logFile
chmod 666 $logFile >> /dev/null 2>&1
