#!/bin/bash
############################################################################
#    KADU INSTALLER (http://kadu.net)                                                       #
#                                                                          #
#    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.,                                       #
#    59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             #
############################################################################

export LC_ALL=pl_PL
export LANG=pl_PL

# Configure, build and install Kadu
perform_install()
{
	if  ./configure `cat log_prefix 2> /dev/null` `cat log_configureoptions 2>/dev/null`; then
		if [[ $advanced_install == true ]]; then
			if make `cat log_makeoptions 2> /dev/null`;then
				perform_make_install
			else
				echo "Instalacja nie powioda si (na etapie make)"
				exit
			fi;
			
		else
			if make; then
				perform_make_install
			else
				echo "Instalacja nie powioda si (na etapie make)"
				exit
			fi;
		fi;
	else
		echo "Instalacja nie powioda si (na etapie ./configure)"
		exit
	fi;
}

perform_make_install()
{
	if [ $UID != "0" ]; then
		$dialog --backtitle "Instalator Kadu" --infobox "Podaj haso roota:" 3 24
		su -c "make install"
	else
		make install
	fi;

}

# make uninstall
uninstall()
{
	$?=0
	$dialog --stdout --defaultno --backtitle "Instalator Kadu" --title "Deinstalacja" --yesno "Czy na pewno chcesz odinstalowa Kadu?" 6 50
		if [ $? == "0" ]; then
			if [ $UID != "0" ]; then
				$dialog --backtitle "Instalator Kadu" --infobox "Podaj haso roota:" 3 24
				su -c "make uninstall"
			else
				make uninstall
			fi; 
		fi;
}

# Some extra options
additional_parameters()
{
	rm -fr log_configureoptions
	$dialog --begin 19 48 --infobox "Nacinij CTRL+C aby wyj" 3 29 --and-widget --separate-output --nocancel --ok-label "OK" --checklist "Jeli chcesz, to moesz wybra dodatkowe opcje kompilacji:" 0 0 0 \
	' --enable-debug' 	'Wcza tryb debug' 0 \
	' --enable-pheaders' 'Wcza obsug prekompilowanych nagwkw' 0 \
	' --with-existing-libgadu' 'Linkuje z istniejcym libgadu' 0 \
	' --disable-sig-handling' 'Bez obsugi sygnaw systemowych (SIGSEGV, ...)' 0 \
	 2>log_configureoptions

}

# Try to predict errors which will break the installation
find_possible_errors()
{
	# Check if installer is run from the current directory:
	test -f ./Instaluj
	if [ $? != "0" ]; then
		$dialog --begin 19 48 --infobox "Nacinij CTRL+C aby wyj" 3 29 --and-widget --stdout --defaultno --backtitle "Instalator Kadu" --title "Niepoprawny katalog" --yesno "Instalator Kadu trzeba uruchamia bezporednio\nz katalogu zawierajcego rda!\nNa pewno kontynuowa? Mog pojawi si bdy!" 7 50
		if [ $? == "1" ]; then
			exit
		fi;
	fi;

	# Check if user is logged in as root:
	if [ $UID != "0" ]; then
		$dialog --begin 19 48 --infobox "Nacinij CTRL+C aby wyj" 3 29 --and-widget --stdout --defaultno --backtitle "Instalator Kadu" --title "Brak uprawnie administratora" --yesno "Nie pracujesz jako root\nMusisz zna to haso, eby zainstalowa Kadu.\nCzy chcesz kontynuowa instalacj?" 7 50
		if [ $? == "1" ]; then
			exit
		fi;
	fi;
	
	# Chceck if the QTDIR variable is set:
	if [[ $QTDIR == "" ]]; then
		$dialog --begin 19 48 --infobox "Nacinij CTRL+C aby wyj" 3 29 --and-widget --stdout --defaultno --backtitle "Instalator Kadu" --title "Brak ustawionej zmiennej \$QTDIR" --yesno "Zmienna \$QTDIR nie jest ustawiona. Moesz mie problemy z kompilacj\nCzy chcesz kontynuowa instalacj?" 6 75
		if [ $? == "1" ]; then
			exit
		fi;
	fi;
}

# Display initial greeting
hello()
{
	$dialog --begin 19 48 --infobox "Nacinij CTRL+C aby wyj" 3 29 --and-widget --backtitle "Instalator Kadu" --ok-label "Kontynuuj" --msgbox "Witaj w programie instalacyjnym Kadu! \
	\nInstalator pomoe Ci zainstalowa lub uaktualni Kadu" 6 75
		
}

# Perform update form SVN
update()
{
	cd ..
	LC_ALL=C svn checkout http://kadu.net/svn/kadu/trunk kadu
	if [[ $? == "0" ]]; then
	$dialog --beep --backtitle "Instalator Kadu" --msgbox "rda Kadu zostay zaktualizowane!" 0 0
	else 
	$dialog --beep --backtitle "Instalator Kadu" --msgbox "Bd przy aktualizacji rde!" 0 0
	fi
	cd kadu
}

# Ask for destination path
pathmenu()
{
	PREF_BAK=$PREFIXPATH
	PREFIXPATH=`$dialog --begin 19 48 --infobox "Nacinij CTRL+C aby wyj" 3 29 --and-widget --stdout --nocancel --ok-label "OK" --backtitle "Instalator Kadu" --inputbox  "Podaj ciek instalacji Kadu" 7 50 "$PREFIXPATH"`
	if [[ $PREFIXPATH != "" ]]; then
		echo -e -n " --prefix=$PREFIXPATH" > log_prefix
	else
	PREFIXPATH=$PREF_BAK
	fi;
}

# Read .config file
prepare_modules_list()
{
	available_modules=
	cd modules
	for dir in *; do \
		if test -f $dir/spec; then \
			available_modules="$available_modules $dir"; \
		fi; \
	done
	for file in *.web; do \
		dir=`basename $file .web`; \
		if test ! -f $dir/spec; then \
			available_modules="$available_modules $dir"; \
		fi; \
	done
	cd ..

	
	all_st_modules_list=
	all_sh_modules_list=
	all_di_modules_list=
	. ./.config; \
	for mod in $available_modules; do \
		echo "option=\$module_$mod" > .temp; \
		. ./.temp; \
		if test -z "$option"; then \
			option=m; \
		fi; \
		case "$option" in
			y) all_st_modules_list="$all_st_modules_list $mod Statyczny on ";; \
			m) all_st_modules_list="$all_st_modules_list $mod Dynamiczny off ";; \
			*) all_st_modules_list="$all_st_modules_list $mod Wyczony off ";; \
		esac; \
		case "$option" in
			y) all_sh_modules_list="$all_sh_modules_list $mod Statyczny off ";; \
			m) all_sh_modules_list="$all_sh_modules_list $mod Dynamiczny on ";; \
			*) all_sh_modules_list="$all_sh_modules_list $mod Wyczony off ";; \
		esac; \
		case "$option" in
			y) all_di_modules_list="$all_sh_modules_list $mod Statyczny off ";; \
			m) all_di_modules_list="$all_sh_modules_list $mod Dynamiczny off ";; \
			*) all_di_modules_list="$all_sh_modules_list $mod Wyczony on ";; \
		esac; \
		case "$option" in
			y) static_modules_list="$static_modules_list $mod ";; \
			m) shared_modules_list="$shared_modules_list $mod ";; \
			*) disabled_modules_list="$disabled_modules_list $mod ";; \
		esac; \
		
	done; \
	rm .temp
	initial_static_modules_list=$static_modules_list
	initial_shared_modules_list=$shared_modules_list
	initial_disabled_modules_list=$disabled_modules_list
}

#Update information about modules - it's essential part for re-creating menus
update_modules_list()
{
	# Update disabled modules
	disabled_modules_list=
		
	for mod in $available_modules; do
		copy_flag=true
		for mod_h in $shared_modules_list; do
			if [[ $mod == $mod_h ]]; then
				copy_flag=false
			fi;
		done;
		for mod_s in $static_modules_list; do
			if [[ $mod == $mod_s ]]; then
				copy_flag=false
			fi;
		done;
		if [[ $copy_flag == true ]]; then
			disabled_modules_list="$disabled_modules_list $mod "
		fi;
		
	done;
	
	# Update static modules
	all_st_modules_list=
	for mod in $available_modules; do
		copy_flag=Wyczony
		
		for mod_s in $static_modules_list; do
			if [[ $mod == $mod_s ]]; then
				copy_flag=true
			fi;
		done;	
		
		for mod_h in $shared_modules_list; do
			if [[ $mod == $mod_h ]]; then
				copy_flag=Dynamiczny
			fi;
		done;		
		
		for mod_d in $disabled_modules_list; do
			if [[ $mod == $mod_d ]]; then
				copy_flag=Wyczony
			fi;
		done;	
		
		if [[ $copy_flag == true ]]; then
			all_st_modules_list="$all_st_modules_list $mod Statyczny on "
		else
			all_st_modules_list="$all_st_modules_list $mod $copy_flag off "
		fi;
	done;
	
	# Update shared modules
	all_sh_modules_list=
	for mod in $available_modules; do
		copy_flag=Wyczony
		for mod_h in $shared_modules_list; do
			if [[ $mod == $mod_h ]]; then
				copy_flag=true
			fi;
		done;	
		
		for mod_d in $disabled_modules_list; do
			if [[ $mod == $mod_d ]]; then
				copy_flag=Wyczony
			fi;
		done;	
		
		for mod_s in $static_modules_list; do
			if [[ $mod == $mod_s ]]; then
				copy_flag=Statyczny
			fi;
		done;
		
		if [[ $copy_flag == true ]]; then
			all_sh_modules_list="$all_sh_modules_list $mod Dynamiczny on "
		else
			all_sh_modules_list="$all_sh_modules_list $mod $copy_flag off "
		fi;
	done;
	
	
}

# Select static modules
select_static()
{
	rm -f log_static_module
	
	$dialog --separate-output --ok-label "OK" --cancel-label "Anuluj" --checklist "Wybierz STATYCZNE moduy do zainstalowania" 0 75 0 \
		$all_st_modules_list 2>log_static_module
	if [[ $? == 0 ]]; then
		static_modules_list=`cat log_static_module`
		update_modules_list
	fi;
}

#Select shared modules
select_shared()
{
	rm -f log_shared_module
	$dialog --separate-output --ok-label "OK" --cancel-label "Anuluj" --checklist "Wybierz DYNAMICZNE moduy do zainstalowania" 0 75 0 \
		$all_sh_modules_list 2>log_shared_module
	if [[ $? == 0 ]]; then
		shared_modules_list=`cat log_shared_module`
 		update_modules_list
	fi;
}

# Write .config file
save_module_list()
{	
	rm -f .config
	for module in $static_modules_list; do
		echo "module_$module=y" >> .config
	done;
	#prepare_modules_list
	for module in $shared_modules_list; do
		echo "module_$module=m" >> .config
	done;
	#prepare_modules_list
	for module in $disabled_modules_list; do
		echo "module_$module=n" >> .config
	done;
}

# Display a menu which allows user to select modules
menu_select_modules()
{
	CONFIGMENUCHOICE=`$dialog --begin 19 48 --infobox "Nacinij CTRL+C aby wyj" 3 29 --and-widget --stdout --no-cancel --backtitle "Instalator Kadu" --title "Wybr moduw" --menu "Wybierz moduy do kompilacji. \
	\nWycznanie statycznych moduw nie jest zalecane. Jeli nie wiesz co wybra, wybierz opcj \"Dalej\". Zostan wybrane moduy domylne" 12 75 3 \
	Statyczne	"Moduy bd kompilowane statycznie" \
	Dynamiczne	"Moduy bd kompilowane dynamicznie" \
	Dalej		"Rozpocznij proces instalacji" `
	
	if [ $CONFIGMENUCHOICE == "Statyczne" ]; then
		select_static
	elif [ $CONFIGMENUCHOICE == "Dynamiczne" ]; then
		select_shared
	elif [ $CONFIGMENUCHOICE == "Dalej" ]; then
		stay_in_loop=0
	fi;

}

display_help()
{
	
	
	cat > ./.temp << "	END"
	
	--------------------------------------------------------
	--- TO NIE JEST UMOWA LICENCYJNA, WIC PRZECZYTAJ TO ---
	--------------------------------------------------------
	
	Szczegowe informacje dotyczce wymaga programowych
	i sprztowych znajduj si na stronie http://kadu.net
	
	W wikszoci przypadkw nie jest konieczne
	dodatkowe konfigurowanie parametrw instalacyjnych
	Kadu. Warto jednak zajrze do sekcji "Moduy" i
	wybra tu rodzaj moduw (statyczne lub dynamiczne)
	oraz te, ktre uwaasz za potrzebne.
	
	UWAGA: Ponisze moduy:
	
	END
	
	cd modules
	for file in *.web; do \
		dir=`basename $file .web`; \
			echo "		- $dir" >> ../.temp
	done
	cd ..
	
	cat >> ./.temp << "	END"
	
	Zostan przez instalator automatycznie pobrane
	z internetu w wersji odpowiedniej do wersji Kadu.
	Konieczne jest wic posiadanie uruchomionego cza
	internetowego. Jeeli modu nie zostanie pobrany,
	zostanie pominity podczas kompilacji.
	
	Po wybraniu opcji "Instaluj" rozpoczyna si proces
	kompilacji i instalacji Kadu. Jeli proces instalacji
	si zatrzyma z komunikatem o bdzie, przejrzyj 
	wywietlone komuinkaty i sprawd w dokumentacji 
	czy podobny problem nie zosta opisany. 
	Jeli nie znajdziesz wskazwek, to przeszukaj 
	forum Kadu (http://kadu.net/forum) w poszukiwaniu 
	odpowiedzi.
	
	Jeli zamierzasz odinstalowa Kadu, to nie kasuj
	tego katalogu, a nastpnie uruchom instalatora
	z parametrem "uninstall". 
	
	DLA ZAAWANSOWANYCH: uruchom instalatora w trybie
	zaawansowanym, aby uzyska dostp do kilku dodatkowych
	opcji instalacyjnych (wybr katalogu docelowego,
	automatyczna aktualizacja do wersji z SVN, rne
	opcje ./configure oraz make). Wyboru wersji
	instalacji dokonasz za chwil.
	END
	$dialog --backtitle "Instalator Kadu" --exit-label "Zrozumiaem" --textbox ./.temp 23 75
	rm -f ./.temp
}

# Select between simple and advanced install
choose_advanced_mode()
{
	CONFIGMENUCHOICE=`$dialog --begin 19 48 --infobox "Nacinij CTRL+C aby wyj" 3 29 --and-widget --stdout --no-cancel --backtitle "Instalator Kadu" --menu "Wybierz rodzaj instalacji - pocztkujcy powinni wybra pierwsz opcj" 9 75 2 \
	Prosty	"Wybiera najczciej spotykane opcje" \
	Zaawansowany	"Pozwala na samodzieln konfiguracj" `
	
	if [ $CONFIGMENUCHOICE == "Zaawansowany" ]; then
		advanced_install=true
	fi;
}

# Ask for some options for make
make_options()
{
	makeoptions=`$dialog --begin 19 48 --infobox "Nacinij CTRL+C aby wyj" 3 29 --and-widget --stdout --nocancel --ok-label "OK" --backtitle "Instalator Kadu" --title "Parametry make" --inputbox  "Jeli potrzebujesz, to podaj parametry programu make (np. -j <numer>)" 8 50 ""`
	if [[ $makeoptions != "" ]]; then
		echo -e -n "$makeoptions" > log_makeoptions
	fi;
}


#-------------------------------------------------------------------------------
#                                   RUN THE INSTALLER
#-------------------------------------------------------------------------------

#0. check for "dialog" and given parameters
step0()
{	
	
	advanced_install=false
	
	which cdialog >/dev/null 2>/dev/null
	if [[ $? != 0 ]]; then

	    which dialog >/dev/null 2>/dev/null
	    if [[ $? != 0 ]]; then

		echo "Instalator wymaga programu \"dialog\" lub \"cdialog\" na FreeBSD. Wyglda na to, e nie masz takiego."
		exit
	    else
	        dialog="dialog"
	    fi;
	else
	    dialog="cdialog"
	fi;

	$dialog --begin 9 0 --infobox "test" 10 10 1>/dev/null 2>/dev/null

	if [[ $? != 0 ]]; then
    		echo "Instalator wymaga programu \"dialog\" lub \"cdialog\" na FreeBSD. Wyglda na to, e twoja wersja nie wspiera rzeczy uytych w tym skrypcie."
		exit	
	fi;

	if [[ $1 == uninstall ]]; then
		uninstall
		exit
	fi;
}

#1. Greetings
step1()
{
	hello
	display_help
	choose_advanced_mode
}

#2. Errors?
step2()
{
	find_possible_errors
}

#3. Ask for update. Do it if necessary
step3()
{
	if [[ $advanced_install == true ]]; then
		$dialog --begin 19 48 --infobox "Nacinij CTRL+C aby wyj" 3 29 --and-widget --stdout --backtitle "Instalator Kadu" --title "Aktualizacja" --ok-label "Takkk" --cancel-label "Nieee" --yesno "Czy chcesz zaktualizowa Kadu do najnowszej wersji z SVN?" 6 50
				if [ $? == "0" ]; then
					update
				fi;
	fi;
}

#4. Ask for destination path
step4()
{	
	PREFIXPATH=/usr
	echo -e -n "--prefix=$PREFIXPATH" > log_prefix
	if [[ $advanced_install == true ]]; then
		pathmenu
	fi;
}

#5. Ask for some extra settings (i.e. debug)
step5()
{
	if [[ $advanced_install == true ]]; then
		additional_parameters
		make_options
	fi;
}

#6. Prepare for selecting modules. Read .config etc.
step6()
{
	prepare_modules_list
	configfile_changed=false
	stay_in_loop=1
	while [[ $stay_in_loop == 1 ]]; do
		menu_select_modules
	done;
}

#7. Save new .config file
step7()
{
	for mod1 in $initial_static_modules_list; do
		match_found=false
		for mod2 in $static_modules_list; do
			if [[ $match_found == false ]]; then
				if [[ $mod1 == $mod2 ]]; then
					match_found=true
				fi;
			fi;
		done;
		if [[ $match_found == false ]]; then
			configfile_changed=true
		fi;
	done;
	
	for mod1 in $initial_shared_modules_list; do
		match_found=false
		for mod2 in $shared_modules_list; do
			if [[ $match_found == false ]]; then
				if [[ $mod1 == $mod2 ]]; then
					match_found=true
				fi;
			fi;
		done;
		if [[ $match_found == false ]]; then
			configfile_changed=true
		fi;
	done;
	
	for mod1 in $initial_disabled_modules_list; do
		match_found=false
		for mod2 in $disabled_modules_list; do
			if [[ $match_found == false ]]; then
				if [[ $mod1 == $mod2 ]]; then
					match_found=true
				fi;
			fi;
		done;
		if [[ $match_found == false ]]; then
			configfile_changed=true
		fi;
	done;
	
	
	if [[ $configfile_changed != false ]]; then
		save_module_list
	fi;
}

#8. Prepare for installation
step8()
{
	$dialog --begin 19 48 --infobox "Nacinij CTRL+C aby wyj" 3 29 --and-widget --stdout --backtitle "Instalator Kadu"  --yesno "Czy chcesz rozpocz proces instalacji?" 6 50
		if [ $? == "1" ]; then
			exit
		fi;
}

#9. Install
step9()
{
perform_install
}

# If you want to skip some stages you can comment appropriate lines below
step0 $1
step1
step2
step3
step4
step5
step6
step7
step8
step9 $1 $2 $3 $4 $5 $6 $7 $8 $9
