#!/bin/bash

# Copyright (C) 2007-2010 PlayOnLinux Team
# Copyright (C) 2008 Pâris Quentin
# Copyright (C) 2009 Łukasz Wojniłowicz

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 551 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 

config_maj()
{
	read line
	if [ ! "$line" = "" ]
	then
		file=$(echo "$line" | cut -d "/" -f 1)
		content=$(echo "$line" | cut -d "/" -f 2)
		download_icon=$(echo "$line" | cut -d "/" -f 3)
		download_min=$(echo "$line" | cut -d "/" -f 4)
		#download_des=$(echo "$line" | cut -d "/" -f 5)

		echo "$content" >> "$file"
		if [ ! "$file" = "10" ] # If not in beta file
		then
			echo "$content" >> "search"
		fi

		if [ "$download_icon" = 1 ]
		then
			if [ ! -e "../icones/$content" ]
			then
				wget "$SITE/V2_data/icones/$content" -q -O "../icones/$content"
			fi
			taille=$(du "../icones/$content")
			taille=${taille:0:1}
			if [ "$taille" = "0" ]
			then
				rm "../icones/$content"
			fi
		fi

		config_maj
	fi
}
maj_check ()
{
		POL_SetupWindow_Init "$PLAYONLINUX/etc/setups/update/top.png"
		if [ "$1" == "--first" ]
		then
			POL_SetupWindow_free_presentation "$(eval_gettext 'First use of PlayOnLinux')" "$(eval_gettext "Welcome to PlayOnLinux's First Use Wizard.")$(eval_gettext "\nPlease make sure you are connected to the Internet.")"
		fi

		if [ "$RMTEMP" == "1" ]
		then
			clean_tmp
		fi

		WebVersion=$(wget -q $SITE/check.txt -O-)
		if [ "$WebVersion" = "" ]
		then
			POL_SetupWindow_message "$(eval_gettext 'The PlayOnLinux website is unavailable.')\n$(eval_gettext "\nPlease make sure you are connected to the Internet.")" "$(eval_gettext 'PlayOnLinux application list update')"
			POL_SetupWindow_Close
		else
			mkdir $REPERTOIRE/configurations/listes/ -p
			cd "$REPERTOIRE/configurations/listes"
			rm * -f 2> /dev/null
			touch 0
			touch 1
			touch 2
			touch 3
			touch 4
			touch 5
			touch 6
			touch 7
			touch 8
			touch 9
			touch 10
			touch "rate"
			touch "download"
			touch "search"
			POL_SetupWindow_wait_next_signal "$(eval_gettext 'Downloading updates...')" "$(eval_gettext 'PlayOnLinux application list update')"
			wget "$SITE/V3_data/repository/get_list.php" -O- -q | config_maj
			if [ "$DOSBOX_SUPPORT" = "1" ]
			then
				wget "$SITE/V3_data/repository/get_list.php?dosbox=1" -O- -q | config_maj
			fi
			wget "$SITE/V3_data/repository/get_top?by=download" -O- -q > download
			wget "$SITE/V3_data/repository/get_top" -O- -q > rate
			POL_SetupWindow_detect_exit
			POL_SetupWindow_Close
		fi
}

menu_principal()
{
	if [ ! -e "$REPERTOIRE/icones/32/" ]
	then
		mkdir -p $REPERTOIRE/icones/32/
		convert -resize 32 "$PLAYONLINUX/etc/playonlinux.png" "$REPERTOIRE/icones/32/playonlinux.png"
	fi
	if [ "$1" = "" ]
	then
		$PYTHON "$PLAYONLINUX/python/mainwindow.py"
	else
		$PYTHON "$PLAYONLINUX/python/mainwindow.py" "$1" "$2"
	fi
}
fonts_install()
{
	if [ ! "$DEJADIS" == "True" ]
	then
		export DEJADIS="True"
		(sleep 1 && install_fonts)&
	fi
}
install_fonts ()
{
	if [ ! -e "$REPERTOIRE/configurations/msfonts_installed" ]
	then
		
		POL_SetupWindow_Init "$PLAYONLINUX/etc/setups/fonts/top.png" "$PLAYONLINUX/etc/setups/fonts/left.jpg"
		POL_SetupWindow_free_presentation "$(eval_gettext 'Microsoft fonts')" "$(eval_gettext "Microsoft fonts aren't installed; I'll install them for you.")$(eval_gettext "\nPlease make sure you are connected to the Internet.")"
		echo -e "---$(eval_gettext " Licence translated in your language ")---
$(eval_gettext "These fonts were provided by Microsoft\n\"in the interest of cross-platform compatibility\".")
$(eval_gettext "This is no longer the case, but they are still available from third parties.")

$(eval_gettext "You are free to download these fonts and use them for your own use,\nbut you may not redistribute them in modified form,\nincluding changes to the file name or packaging format.")\n" > $REPERTOIRE/tmp/licence
		echo "---$(eval_gettext " Original licence ")---
These fonts were provided by Microsoft \"in the interest of
cross-platform compatibility\".
This is no longer the case, but they are still available from
third parties.

You are free to download these fonts and use them for your own use,
but you may not redistribute them in modified form, including changes
to the file name or packaging format." >> $REPERTOIRE/tmp/licence
		cat $REPERTOIRE/tmp/licence

		POL_SetupWindow_licence "$(eval_gettext 'Please read and accept the following:')" "$(eval_gettext 'Microsoft fonts')" "$REPERTOIRE/tmp/licence"
		WebVersion=$(wget -q $SITE/check.txt -O-)
		if [ "$WebVersion" == "" ]
		then
			POL_SetupWindow_message "$(eval_gettext 'The PlayOnLinux website is unavailable.')$(eval_gettext "\nPlease make sure you are connected to Internet.")" "$(eval_gettext 'Microsoft fonts')"
			POL_SetupWindow_Close
		else
			rm $REPERTOIRE/fonts/ -r 2> /dev/null
			rm $REPERTOIRE/fonts 2> /dev/null
			rm $REPERTOIRE/configurations/fonts_installed 2> /dev/null
			FONTDIR=$REPERTOIRE/fonts/
			mkdir -p $FONTDIR
			FONTS_INSTALLER="andale32.exe arialb32.exe arial32.exe comic32.exe courie32.exe georgi32.exe impact32.exe times32.exe trebuc32.exe verdan32.exe webdin32.exe"
			cd $FONTDIR
			PULSE=1
			POL_SetupWindow_pulsebar "$(eval_gettext 'Downloading fonts')" "$(eval_gettext 'Microsoft fonts')"

			for font in $FONTS_INSTALLER
			do
			 sleep 0.1
			 POL_SetupWindow_set_text "$(eval_gettext 'Downloading: ')$font..."
			 echo "$(eval_gettext 'Downloading: ')$font..."
			 wget "http://heanet.dl.sourceforge.net/sourceforge/corefonts/$font" -q
			 PULSE=$(( PULSE + 8 ))
			 POL_SetupWindow_pulse $PULSE
			done

			echo "$(eval_gettext 'Downloading: ')tahoma32.exe"
			POL_SetupWindow_set_text "$(eval_gettext 'Downloading: ')tahoma32.exe"
			wget http://download.microsoft.com/download/office97pro/fonts/1/w95/en-us/tahoma32.exe -q
			POL_SetupWindow_pulse 100
			sleep 1
			PULSE=1
			POL_SetupWindow_detect_exit
			POL_SetupWindow_pulsebar "$(eval_gettext 'Installing fonts')" "$(eval_gettext 'Microsoft fonts')"

			for font in $FONTS_INSTALLER
			do
			 sleep 0.1
			 POL_SetupWindow_set_text "$(eval_gettext 'Installing: ')$font..."
			 echo "$(eval_gettext 'Installing: ')$font..."
			 cabextract "$font" > /dev/null
			 PULSE=$(( PULSE + 8 ))
			 POL_SetupWindow_pulse $PULSE
			 sleep 0.1
			done

			POL_SetupWindow_set_text "$(eval_gettext 'Installing: ')tahoma32.exe"
			echo "$(eval_gettext 'Installing: ')tahoma32.exe"
			cabextract tahoma32.exe > /dev/null
			POL_SetupWindow_pulse 100
			sleep 1
			rm *.exe
			rm *.done
			rm *.dll
			rm *.inf
			rm *.txt
			touch "$REPERTOIRE/configurations/msfonts_installed"
			POL_SetupWindow_message "$(eval_gettext 'Microsoft fonts have been installed successfully.')" "$(eval_gettext 'Microsoft fonts')"
			POL_SetupWindow_Close

		fi
	fi
}
install_plugins () # Install defaults plugin into home directory
{
	
	#declaration de variables locale
	#le P c'est pour euh POL/Package/?
	local Puid Pfichier PinstDir PplugStatus PverStr Pversion plugStatus
	#la le U par contre c'est pour user
	local Uuid Ufichier UinstDir UplugStatus UverStr Uversion Uligne
	# _2 parce que avant c'était pas pareil 
	readonly ULST=$POL_USER_ROOT/configurations/plugins_2
	touch $ULST

	#lecture du fichier ligne/ligne
	while read ligne
	do
		#sauter les lignes qui commence par #
		grep -q '^#' <<< $ligne && continue
		#et les lignes vides ... parce que ça fait plus propre
		grep -q '^$' <<< $ligne && continue

		#paf pif split!
		Puid=$(cut -d';' -f1 <<< $ligne)
		Pfichier=$(cut -d';' -f2 <<< $ligne)
		PinstDir=$(cut -d';' -f3 <<< $ligne)
		PplugStatus=$(cut -d';' -f4 <<< $ligne)
		PverStr=$(cut -d';' -f5 <<< $ligne)
		Pversion=$(cut -d';' -f6 <<<$ligne)
		
		echo "$(eval_gettext "Checking plugin: ")$PinstDir..."
		
		Uligne=$(grep "^$Puid;" $ULST)
		#tres important le ; !
		
		plugStatus="$PplugStatus" #ouai ouai c'est débile d'utiliser 2 variables pour la même chose :D

		#chk si la ligne existe déjà
		if [ -n "$Uligne" ] ; then
			#oui

			#la même mais avec un U =) 
			#y a des trucs dont on se fiche mais bon c/c is great
			Uuid=$(cut -d';' -f1 <<< $Uligne)
			Ufichier=$(cut -d';' -f2 <<< $Uligne)
			UinstDir=$(cut -d';' -f3 <<< $Uligne)
			UplugStatus=$(cut -d';' -f4 <<< $Uligne)
			UverStr=$(cut -d';' -f5 <<< $Uligne)
			Uversion=$(cut -d';' -f6 <<<$Uligne)

			#chk version
			#si la version du P est la même ou plus old que l'U on passe au plugin suivant
			[ $Pversion -gt $Uversion ] || continue

			#bon ben la c'est sur le gus a vieux truc
			echo "   -->$(eval_gettext 'Updating plugin. Previous: ')'$UverStr'/$Uversion. $(eval_gettext 'New: ')'$PverStr'/$Pversion."
			
			#est ce que le plugin était déjà actif?
			#UplugStatus="disable"
			[ -f "$POL_USER_ROOT/plugins/$UinstDir/enabled" ] && plugStatus="enable"
			#la c'est barbare ... si déjà actif on force l'update actif ...
			#sinon dépend du plugins.lst


			#on vire l'ancienne installation (utile si le plugin change de place)
			#les perdants sont les plugins qui gardent des fichiers de config dans leur dossier ... tant pis pour eux
			rm -rf "$POL_USER_ROOT/plugins/$UinstDir/"

			#on vire la ligne dans le fichier utilisateur 
			grep -v "^$Puid;" "$ULST" > "$POL_USER_ROOT/tmp/ulst.tmp"
			mv -f "$POL_USER_ROOT/tmp/ulst.tmp" "$ULST"
			#voilà ménage fait plus qu'à installer
		fi

		echo "   -->$(eval_gettext "Installing plugin: ")'$PinstDir'."
		#là on installe
		"$PLAYONLINUX/playonlinux-pkg" -i "$PLAYONLINUX/plugins/$Pfichier" > /dev/null

		## =~ ok pour enable et enabled
		#active or nto
		if [[ "$plugStatus" =~ "enable" ]]
		then
			touch "$POL_USER_ROOT/plugins/$PinstDir/enabled"
		fi

		#et on enregistre qu'on vient de faire
		echo "$Puid;$Pfichier;$PinstDir;$plugStatus;$PverStr;$Pversion" >> $ULST

	#est voilà on continue .... et moi j'ai fait cramer mes patates
	done < $PLAYONLINUX/plugins/plugins.lst
}
construire_repertoire_personnel ()
{
	mkdir "$REPERTOIRE/wineprefix/" -p
	mkdir "$REPERTOIRE/configurations/installed/" -p
	mkdir "$REPERTOIRE/configurations/options/" -p
	mkdir "$REPERTOIRE/configurations/icones/" -p
	mkdir "$REPERTOIRE/configurations/messages_shown/" -p
	mkdir "$REPERTOIRE/tmp" -p
	mkdir "$REPERTOIRE/logs" -p
	mkdir "$REPERTOIRE/ressources" -p
	mkdir "$REPERTOIRE/icones/full_size" -p
	mkdir "$REPERTOIRE/WineVersions" -p
	mkdir "$REPERTOIRE/plugins" -p
	mkdir "$REPERTOIRE/configurations/guis" -p
	mkdir "$REPERTOIRE/configurations/configurators" -p
	mkdir "$REPERTOIRE/configurations/setups" -p
	touch "$REPERTOIRE/configurations/last_version"
}
start_pol ()
{
	if [ `id -u` = 0 ]
	then
		if [ `question "$(eval_gettext "You are running PlayOnLinux as root.\n\n")$(eval_gettext "Please note that it is very dangerous to run Wine programs as root: you are vulnerable to viruses and other bad stuff.\n\n")$(eval_gettext "PlayOnLinux is not reponsible for any damage to your system.\n\n")$(eval_gettext "Are you sure you want to start PlayOnLinux?")" "$(eval_gettext "Warning!")"` = 1 ]
		then
			exit
		fi
	fi
	if [ "$1" = "--run" ]
	then
		#Arg contient tout apres l'option --run
		#Supporte le lancement de jeu avec option POL >> 1.7.5
		Arg=$(echo $@ | cut -b7-)
		Arg=${Arg//"$2"/""}
		Arg=${Arg:1}
		lancer "$2" "$Arg"
		exit 0
	elif [ "$1" = "--debug" ]
	then
		bash "$PLAYONLINUX/bash/system_info" "$1" "$2"
		#Arg contient tout apres l'option --run
		#Supporte le lancement de jeu avec option POL >> 1.7.5
		Arg=$(echo $@ | cut -b7-)
		Arg=${Arg//"$2"/""}
		Arg=${Arg:1}
		lancer "$2" "$Arg --debug"
		exit 0
	fi

	cfg_check 
	construire_repertoire_personnel
	if [ ! -d "$HOME/.PlayOnLinux/configurations/listes" ]
	then
		maj_check --first
	else
		bash "$PLAYONLINUX/bash/check_maj_" &
	fi
	fonts_install
	install_plugins

	check_new_pol
	retChkNew=$?
	#retourne:
	# 0 = pas de nouvelle version
	# 1 = nouvelle version dispo
	# 2 = pas internet ?
	# 3 = version de dev utilise
	# 4 = pas le site officiel, utilisation du plugin offline ?
	#if [ ! "$NEW_VERSION" = "" ]
	if [ "$retChkNew" != "0" ]
	then
		menu_principal $retChkNew "$NEW_VERSION"
	else
		menu_principal
	fi
}
clean_tmp ()
{
	rm "$REPERTOIRE/tmp/" -rf
	mkdir "$REPERTOIRE/tmp" -p
}

fixme () 
{
	#generic function for all FIXME
	#PLEASE DO NOT TRANSLATE ANY OF THIS PART !
	#call this function by 'fixme "path to file" "function_to_fix" "comment of fix to do"'
	local IFS='::'
	echo "FIXME::POL::$*"
}
check_new_pol () 
{
	#retourne:
	# 0 = pas de nouvelle version
	# 1 = nouvelle version dispo
	# 2 = pas internet ?
	# 3 = version de dev utilise
	# 4 = pas le site officiel, utilisation du plugin offline ?
	local retVal=0
	if [ ! "$ALREADY_CHECK_ONLINE" ]
	then
		WebVersion=$(wget -q "$SITE/version2.php?v=$VERSION" -T 1 -O-)
		if [ "$WebVersion" = "" ]
		then
			retVal=2
		elif [ $(convertVersionToInt $WebVersion) -gt $(convertVersionToInt $VERSION) ]
		then
			export NEW_VERSION="$WebVersion"
			retVal=1
		elif [ $(convertVersionToInt $WebVersion) -lt $(convertVersionToInt $VERSION) ]
		then
			#using a dev release!
			retVal=3
		fi
		if [ "$SITE" != "http://repository.playonlinux.com/" ]
		then
			#not using POL website
			retVal=4
		fi
		export ALREADY_CHECK_ONLINE=true
	fi
	return $retVal
}

sudo ()
{
	echo "$(eval_gettext "This function is disabled in the PlayOnlinux environment.")"
	return 1
}
gksudo ()
{
	echo "$(eval_gettext "This function is disabled in the PlayOnlinux environment.")"
	return 1
}
gksu ()
{
	echo "$(eval_gettext "This function is disabled in the PlayOnlinux environment.")"
	return 1
}
su ()
{
	echo "$(eval_gettext "This function is disabled in the PlayOnlinux environment.")"
	return 1
}
kdesu ()
{
	echo "$(eval_gettext "This function is disabled in the PlayOnlinux environment.")"
	return 1
}
kdesudo ()
{
    echo "$(eval_gettext "This function is disabled in the PlayOnlinux environment.")"
	return 1
}

/usr/bin/sudo ()
{
	echo "$(eval_gettext "This function is disabled in the PlayOnlinux environment.")"
	return 1
}
/usr/bin/gksudo ()
{
	echo "$(eval_gettext "This function is disabled in the PlayOnlinux environment.")"
	return 1
}
/usr/bin/gksu ()
{
	echo "$(eval_gettext "This function is disabled in the PlayOnlinux environment.")"
	return 1
}
/usr/bin/su ()
{
	echo "$(eval_gettext "This function is disabled in the PlayOnlinux environment.")"
	return 1
}
/usr/bin/kdesu ()
{
	echo "$(eval_gettext "This function is disabled in the PlayOnlinux environment.")"
	return 1
}
/usr/bin/kdesudo ()
{
    echo "$(eval_gettext "This function is disabled in the PlayOnlinux environment.")"
	return 1
}

RefreshLibs()
{
	source "$PLAYONLINUX/lib/sources"
}
POL_Call() 
{
	if [ ! "$1" = "" ]
	then	
		OLD_PC_DIR="$PWD"
		cd "$REPERTOIRE/tmp/"
		wget -q "$SITE/V3_data/repository/get_file.php?version=playonlinux-$VERSION&id=$1" -O- > "$1"
		source $@
		cd "$OLD_PC_DIR"
	fi
}

function convertVersionToInt ()
{
## convert version string to an (increasing) integer by an mathematic formul
# on explose le string en 4 parties
	local versionP1 versionP2 versionP3 versionDev=0 versionInt
	versionP1=$(cut -d'.' -f1 <<< $1)
	versionP2=$(cut -d'.' -f2 <<< $1)
	versionP3=$(cut -d'.' -f3 <<< $1 | cut -d '-' -f1)
	#rajouter pour les vesions de dev -> la version stable peut sortir
	#les personnes qui utilise la version de dev sont quand même informé d'une MAJ
	#ex 3.8.1 < 3.8.2-dev < 3.8.2
	if  grep -q 'dev' <<< $1 ; then
		versionDev=-5
	fi
	#on fait des maths partie1 elever au cube et multiplier par 1000
	let "versionP1 = versionP1 * versionP1 * versionP1 * 1000"
	#partie 2 
	let "versionP2 = versionP2 * versionP2 * 100"
	#partie 3
	let "versionP3 = versionP3 * 10"
	#versionDev ? 
	let "versionDev = versionDev"  
	#on additionne le tout
	let "versionInt = versionP1 + versionP2 + versionP3 + versionDev"
	echo $versionInt
	#echo $versionInt 1>&2
}

