#!/bin/sh

# Si l'utilisateur est bien root
if [ "$(id -u)" -ne 0 ]
then
	echo "You must be root"
	exit 1
fi


# ----------------------------
#  Installation de Teamviewer
#

# Demande confirmation
zenity --question --text="This will install Teamviewer" --cancel-label=Cancel --ok-label=Continue

# Si l'utilisateur a annulé
if [ $? -ne 0 ]
then
	exit 2
fi

ROOT_DIR="$(dirname "$(readlink -f "$0")")"
DATA_DIR="$ROOT_DIR"/.data
ZENITY_TITLE="Teamviewer Installer"
LOGFILE=/tmp/teamviewer-install.log

# Supression d'un log précédent
rm -f "$LOGFILE"

# Wrapper pour zenity
{
	# Ajout des dépots Debian
	echo "# Adding Debian repository"
	echo "deb http://ftp.debian.org/debian/ $DISTRIB_CODENAME main contrib" > /etc/apt/sources.list.d/caldera-extra-tools.list 2> "$LOGFILE"
	echo "10"

	# Ajout de l'architecture i386
	echo "# Adding i386 architecture to dpkg"
	dpkg --add-architecture i386 >> "$LOGFILE" 2>&1
	echo "20"

	# Mise à jour du cache d'apt
	echo "# Updating apt-get cache"
	DEBIAN_FRONTEND=noninteractive apt-get --quiet --assume-yes --allow-unauthenticated update >> "$LOGFILE" 2>&1
	echo "30"

	# Installation manuelle des dépendances 64 bits du .deb via apt-get
	echo "# Installing Teamviewer dependencies"
	
	DEPENDANCES="libqt5opengl5 libqt5printsupport5 libqt5qml5 libqt5quick5 libqt5sql5 libqt5sql5-sqlite libqt5webkit5 qml-module-qtgraphicaleffects qml-module-qtquick-controls qml-module-qtquick-dialogs qml-module-qtquick-layouts qml-module-qtquick-privatewidgets qml-module-qtquick-window2 qml-module-qtquick2 libqt5x11extras5"

	# On installe les dépendances
	DEBIAN_FRONTEND=noninteractive apt-get --quiet --assume-yes --allow-unauthenticated install $DEPENDANCES >> "$LOGFILE" 2>&1

	APT_RES=$?
	echo "80"

	# Si apt s'est bien déroulé
	if [ "$APT_RES" -eq 0 ]
	then
		echo "# Installing Teamviewer package"
		dpkg -i "$DATA_DIR"/teamviewer_13.2.26559_amd64.deb >> "$LOGFILE" 2>&1
		DPKG_RES=$?
		echo "100"

		# Si l'installation s'est bien passée
		if [ "$DPKG_RES" -eq 0 ]
		then
			zenity --info  --title="$ZENITY_TITLE" --text="Installation finished"
		else
			zenity --error --title="$ZENITY_TITLE" --text="An error occured during dependencies installation : $LOGFILE"
		fi
	else
		zenity --error --title="$ZENITY_TITLE" --text="An error occured during installation : $LOGFILE"
	fi
} | zenity --progress --percentage=0 --title="$ZENITY_TITLE" --text="Installing..." --auto-close --no-cancel

