#!/bin/bash


# Const variables
readonly INSTALLER_VERSIONCODE=3
readonly URL_INSTALLER_VERSIONCHECK="https://pi-control.de/service/v1/bash_installer/"


# Temp variables
distribution=""
distributionCode=0

webserver=""
webroot=""
customWebpath=""
customPort=80

phpVersion=""


# Other variables
hostname=$(cat /proc/sys/kernel/hostname)
ipaddress=$(ip route get 8.8.8.8 | awk '{print $NF; exit}')


# Functions
function getDistribution () {
	distro="$(lsb_release -si 2>/dev/null)"

	if [ "$distro" == "" ]
	then
		distro="$(cat /etc/*-release | grep -E ^ID= | cut -d= -f2)"
	fi

	if echo "$distro" | grep -Eiq raspbian
	then
		distribution="Raspbian"
		return
	fi

	distribution="$distro"
}

function getDistributionCode () {
	distrocode="$(lsb_release -sr 2>/dev/null)"

	if [ "$distrocode" == "" ]
	then
		distrocode="$(cat /etc/*-release | grep -E ^VERSION_ID= | grep -Eo [[:digit:]])"
	fi

	if echo "$distrocode" | grep -Eq 7
	then
		distributionCode="7"
		return
	fi

	if echo "$distrocode" | grep -Eq 8
	then
		distributionCode="8"
		return
	fi

	if echo "$distrocode" | grep -Eq 9
	then
		distributionCode="9"
		return
	fi

	distributionCode="$distrocode"
}

function checkDistribution () {
	if [ "$distribution" != "Raspbian" ]
	then
		return 1
	fi

	if [[ "$distributionCode" != "7" && "$distributionCode" != "8"  && "$distributionCode" != "9" ]]
	then
		return 2
	fi

	return 0
}

function getWebserver () {
	response="$(curl -I -s --max-time 20 127.0.0.1 | grep Server)"

	if echo "$response" | grep -Eiq apache
	then
		webserver="Apache2"
		webroot="/var/www/html/"
		return
	fi

	if echo "$response" | grep -Eiq nginx
	then
		webserver="Nginx"
		webroot="/var/www/html/"
		return
	fi

	if echo "$response" | grep -Eiq lighttpd
	then
		webserver="Lighttpd"
		webroot="/var/www/html/"
		return
	fi

	if [ "$response" != "" ]
	then
		webserver="unknown"
	else
		webserver="nothing"

		if command -v apache2 > /dev/null 2>&1
		then
			webserver="Apache2"
			webroot="/var/www/html/"
		fi

		if command -v nginx > /dev/null 2>&1
		then
			webserver="Nginx"
			webroot="/var/www/html/"
		fi

		if command -v lighttpd > /dev/null 2>&1
		then
			webserver="Lighttpd"
			webroot="/var/www/html/"
		fi
	fi
}

function installWebserver () {
	if [[ "$webserver" == "Apache2" || "$webserver" == "Nginx" || "$webserver" == "Lighttpd" ]]
	then
		printf "\e[32m%s (%s)\n" "Vorhanden" "$webserver"
	elif [[ "$webserver" == "nothing" ]]
	then
		printf "\e[31m%s\e[0m\n" "Nicht vorhanden! Installiere Nginx..."

		sleep 1
		apt-get -qy install nginx && printf "\n\e[32m%s\n" "Das Paket wurde erfolgreich installiert."
		rm /etc/nginx/sites-enabled/default
	elif [[ "$webserver" == "unknown" ]]
	then
		printf "\e[31m%s\n" "Nicht erkannt! Manuelle Eingabe erforderlich."
		printf "\e[93m%s \e[0m" "Bitte gebe den absoluten Pfad zum Webverzeichnis an:"
		read webroot </dev/tty
		
		webroot="$(readlink -m /$webroot)"
		#webroot="$(echo "$webroot" | sed -r 's|^/*(.*)/+|\1|g')"
		
		while ! [ -d "$webroot" ]
		do
			printf "\e[31m%s %s %s\n\e[0m" "Der Pfad zum Webverzeichnis" "$webroot" "existiert nicht."
			printf "\e[93m%s \e[0m" "Bitte gebe den absoluten Pfad zum Webverzeichnis an:"
			read webroot </dev/tty
				
			webroot="$(readlink -m /$webroot)"
			#webroot="$(echo "$webroot" | sed -r 's|^/*(.*)/+|\1|g')"
		done
	fi
}

function checkWebroot () {
	webroots=(
			"/var/www/html/"
			"/var/www/"
			"/usr/share/nginx/"
		)
	count=0

	while [ ! -d "$webroot" ]
	do
		if [ "$count" -gt 2 ]
		then
			webserver="unknown"
		fi

		if [ "$webserver" != "unknown" ]
		then
			webroot=${webroots[count]}
			count=$(($count + 1))
		elif [ "$webserver" == "unknown" ]
		then
			printf "\e[31m%s %s %s\n" "Verzeichnis" "$webroot" "wurde nicht gefunden!"
			printf "\e[93m%s \e[0m" "Bitte gebe den absoluten Pfad zum Webverzeichnis an:"
			read webroot </dev/tty
			printf "\n"

			webroot="$(readlink -m $webroot)"
		fi
	done

	webroot="$(readlink -m $webroot)"

	printf "\e[32m%s%s%s\n" "Vorhanden (" "$webroot" ")"
}

function installPHP () {
	phpEngine=""
	phpCli=""
	phpCurl=""
	phpMcrypt=""
	phpZip=""
	phpPear=""
	phpSSH=""
	phpApacheLib=""

	if [ "$(command -v php)" != "" ]
	then
		phpVersion="$(php -v | grep -Eo '^PHP [[:digit:]]+' | grep -Eo '[[:digit:]]+')"
	fi

	if [ "$phpVersion" == "5" ]
	then
		if [[ "$(command -v php5-fpm)" == "" && "$(command -v php5-cgi)" == "" ]]
		then
			phpEngine="php5-fpm"
		fi

		if [ "$(dpkg -l | grep -E '^ii[ ]+php5-cli.*')" == "" ]
		then
			phpCli="php5-cli"
		fi

		if [ "$(dpkg -l | grep -E '^ii[ ]+php5-curl.*')" == "" ]
		then
			phpCurl="php5-curl"
		fi

		if [ "$(dpkg -l | grep -E '^ii[ ]+php5-mcrypt.*')" == "" ]
		then
			phpMcrypt="php5-mcrypt"
		fi

		#if [ "$(dpkg -l | grep -E '^ii[ ]+php5-zip.*')" == "" ]
		#then
		#	phpZip="php5-zip"
		#fi

		if [ "$(dpkg -l | grep -E '^ii[ ]+php5-ssh2.*')" == "" ]
		then
			phpSSH="php5-ssh2"
		fi

		if [ "$webserver" == "Apache2" ]
		then
			if [ "$(dpkg -l | grep -E '^ii[ ]+libapache2-mod-php5.*')" == "" ]
			then
				phpApacheLib="libapache2-mod-php5"
			fi
		fi

		if [[ "$phpSSH" != "" && "$distributionCode" == "9" ]]
		then
			printf "\e[31m%s%s%s\n" "Unvollstaendig (PHP " "$phpVersion" ")"
			printf "\e[31m%s\n%s\n" "Beachte, unter Debian Stretch koennen standardmaeßig nicht alle noetigen PHP-Pakete installiert werden." "Schaue dazu bitte unbedingt hier: https://pi-control.de/help/?s=16"
			printf "\e[93m%s " "Weiter mit beliebiger Taste..."
			read -sn1
			printf "\n\e[96m%s " "Pruefe PHP..."

			# Clear because not possible to install
			phpSSH=""
		fi
	fi

	if [ "$phpVersion" == "7" ]
	then
		phpPrefix="php"

		if [ "$(command -v php7.0)" != "" ]
		then
			phpPrefix="php7.0"
		fi

		if [ "$(command -v php7.1)" != "" ]
		then
			phpPrefix="php7.1"
		fi

		if [ "$(command -v php7.2)" != "" ]
		then
			phpPrefix="php7.2"
		fi

		if [[ "$(dpkg -l | grep -E '^ii[ ]+'${phpPrefix}'-fpm.*')" == "" && "$(dpkg -l | grep -E '^ii[ ]+'${phpPrefix}'-cgi.*')" == "" ]]
		then
			phpEngine="php-fpm"
		fi

		if [[ "$(dpkg -l | grep -E '^ii[ ]+'${phpPrefix}'-cli.*')" == "" && "$(dpkg -l | grep -E '^ii[ ]+php-cli.*')" == "" ]]
		then
			phpCli="php-cli"
		fi

		if [[ "$(dpkg -l | grep -E '^ii[ ]+'${phpPrefix}'-curl.*')" == "" && "$(dpkg -l | grep -E '^ii[ ]+php-curl.*')" == "" ]]
		then
			phpCurl="php-curl"
		fi

		if [[ "$(dpkg -l | grep -E '^ii[ ]+'${phpPrefix}'-mcrypt.*')" == "" && "$(dpkg -l | grep -E '^ii[ ]+php-mcrypt.*')" == "" ]]
		then
			phpMcrypt="php-mcrypt"
		fi

		if [[ "$(dpkg -l | grep -E '^ii[ ]+'${phpPrefix}'-zip.*')" == "" && "$(dpkg -l | grep -E '^ii[ ]+php-zip.*')" == "" ]]
		then
			phpZip="php-zip"
		fi

		if [[ "$(dpkg -l | grep -E '^ii[ ]+'${phpPrefix}'-ssh2.*')" == "" && "$(dpkg -l | grep -E '^ii[ ]+php-ssh2.*')" == "" ]]
		then
			phpSSH="php-ssh2"
		fi

		if [ "$webserver" == "Apache2" ]
		then
			if [ "$(dpkg -l | grep -E '^ii[ ]+libapache2-mod-php7.0.*')" == "" ]
			then
				phpApacheLib="libapache2-mod-php7.0"
			fi
		fi
	fi

	#if [ "$(dpkg -l | grep -E '^ii[ ]+php-pear.*')" == "" ]
	#then
	#	phpPear="php-pear"
	#fi

	if [ "$phpVersion" == "" ]
	then
		if [ "$webserver" == "Apache2" ]
		then
			phpApacheLib="libapache2-mod-php5"

			if [ "$distributionCode" -ge "9" ]
			then
				phpApacheLib="libapache2-mod-php7.0"
			fi
		fi

		printf "\e[31m%s\e[0m\n" "Nicht vorhanden! Wird installiert..."

		if [ "$distributionCode" -ge "9" ]
		then
			eval apt-get -qy install php7.0-fpm php7.0-cli php7.0-curl php7.0-mcrypt php7.0-zip php7.0-ssh2 $phpApacheLib && printf "\n\e[32m%s\n" "PHP wurde erfolgreich installiert." || exit 1
		else
			eval apt-get -qy install php5-fpm php5-cli php5-curl php5-mcrypt php5-ssh2 $phpApacheLib && printf "\n\e[32m%s\n" "PHP wurde erfolgreich installiert." || exit 1
		fi
	elif [[ "$phpEngine" != "" || "$phpCli" != "" || "$phpCurl" != "" || "$phpMcrypt" != ""  || "$phpZip" != "" || "$phpSSH" != "" || "$phpApacheLib" != "" ]]
	then
		printf "\e[31m%s\e[0m\n" "Nicht vollstaendig! Wird installiert..."

		eval apt-get -qy install $phpEngine $phpCli $phpCurl $phpMcrypt $phpZip $phpSSH $phpApacheLib && printf "\n\e[32m%s\n" "PHP wurde erfolgreich installiert." || exit 1
	else
		printf "\e[32m%s%s%s\n" "Vorhanden (PHP " "$phpVersion" ")"
	fi
}

function configureWebserver () {
	if [[ "$webserver" == "nothing" || "$webserver" == "Nginx" ]]
	then
		printf "\n\e[93m%s\n" "[1] http://${hostname}/ (Standardauswahl)"
		printf "\e[93m%s\n" "[2] http://${hostname}/pic (Unterverzeichnis; \"pic\" kann selbst gewaehlt werden)"
		printf "\e[93m%s\n" "[3] http://${hostname}:1693 (Port; \"1693\" kann selbst gewaehlt werden)"
		printf "\e[93m%s \e[0m" "Wie soll Pi Control erreichbar sein? [1-3]"
		read answer < /dev/tty

		case $answer in
		2)
			configureCustomWebpath
			;;
		3)
			configureCustomPort
			
			if [ "$webroot" == "/var/www/html" ]
			then
				webroot="/var/www/picontrol"
				mkdir -p "$webroot"
			fi
			
			ipaddress="$ipaddress:$customPort"
			hostname="$hostname:$customPort"
			
			;;
		*)
			;;
		esac
		
		if [[ "$webserver" == "nothing" || "$customPort" != "" ]]
		then
			if [ "$phpVersion" == "5" ]
			then
				if [ "$(dpkg -l | grep -E '^ii[ ]+php5-cgi.*')" != "" ]
				then
					fastcgiPass="fastcgi_pass 127.0.0.1:9000;"
				elif [ "$(dpkg -l | grep -E '^ii[ ]+php5-fpm.*')" != "" ]
				then
					fastcgiPass="fastcgi_pass unix:/var/run/php5-fpm.sock;"
				fi
			else
				if [ "$(dpkg -l | grep -E '^ii[ ]+'${phpPrefix}'-cgi.*')" != "" ]
				then
					fastcgiPass="fastcgi_pass 127.0.0.1:9000;"
				elif [ "$(dpkg -l | grep -E '^ii[ ]+'${phpPrefix}'-fpm.*')" != "" ]
				then
					fastcgiPass="fastcgi_pass unix:/var/run/php/$phpPrefix-fpm.sock;"
				fi
			fi
			
			nginxConfig="picontrol"
			
			if [ -a "/etc/nginx/sites-available/picontrol" ]
			then
				printf "\e[31m%s\n\e[93m%s \e[0m" "Es existiert bereits eine Konfigurationsdatei unter /etc/nginx/sites-available/picontrol." "Datei ueberschreiben? [j/n]"
				read answer < /dev/tty

				if [[ "$answer" == "j" || "$answer" == "J" || "$answer" == "y" || "$answer" == "Y" ]]
				then
					mv /etc/nginx/sites-available/picontrol /etc/nginx/sites-available/picontrol.old
					printf "\e[31m%s\e[0m\n" "Die bestehende Konfigurationsdatei wurde in picontrol.old umbenannt und mit der neuen ersetzt."
				else
					timeDate=$(date +"%Y%m%d%H%M")
					nginxConfig="picontrol_$timeDate"
					printf "\e[31m%s\e[0m\n" "Die neue Konfigurationsdatei wurde unter dem Namen $nginxConfig angelegt."
				fi
			fi
			
			printf "server {
	listen %s default_server;
	listen [::]:%s default_server;

	root %s;

	index index.php index.html;
	server_name _;

	location / {
		try_files \$uri \$uri/ =404;
	}

	location ~ \.php\$ {
		include snippets/fastcgi-php.conf;
		%s
	}

	location ~ /\.ht {
		deny all;
	}
}" "$customPort" "$customPort" "$webroot" "$fastcgiPass"  > /etc/nginx/sites-available/$nginxConfig
			ln -sf /etc/nginx/sites-available/$nginxConfig /etc/nginx/sites-enabled/$nginxConfig
		fi
	else
		printf "\n\e[93m%s\n" "[1] http://${hostname}/ (Standardauswahl)"
		printf "\e[93m%s\n" "[2] http://${hostname}/pic (Unterverzeichnis; \"pic\" kann selbst gewaehlt werden)"
		printf "\e[93m%s \e[0m" "Wie soll Pi Control erreichbar sein? [1-2]"
		read answer < /dev/tty

		case $answer in
		2)
			configureCustomWebpath
			;;
		*)
			;;
		esac
	
		
	fi
}

function configureCustomWebpath () {
	createCustomWebpath=true

	printf "\e[93m%s \e[0m" "Bitte gebe einen Ordnernamen an:"
	read customWebpath < /dev/tty

	customWebpath="$(readlink -m /$customWebpath)"
	#customWebpath="$(echo "$customWebpath" | sed -r 's|^/*(.*)/+|\1|g')"

	while [[ "$customWebpath" != "" && -d "$(readlink -m $webroot/$customWebpath)" ]]
	do
		printf "\e[31m%s \e[93m%s \e[0m" "Der Ordner unter $webroot/$customWebpath/ existiert bereits." "Ordner beibehalten? [j/n]"
		read answer < /dev/tty

		if [[ "$answer" == "j" || "$answer" == "J" || "$answer" == "y" || "$answer" == "Y" ]]
		then
			createCustomWebpath=false
			break
		else
			printf "\e[93m%s \e[0m" "Bitte gebe einen neuen Ordnernamen an:"
			read customWebpath < /dev/tty

			customWebpath="$(readlink -m /$customWebpath)"
			#customWebpath="$(echo "$customWebpath" | sed -r 's|^/*(.*)/+|\1|g')"
		fi
	done

	if [ "$createCustomWebpath" = true ]
	then
		mkdir -p "$webroot/$customWebpath"

		printf "\e[32m%s" "Der Ordner fuer Pi Control wurde erfolgreich erstellt."
	fi

	if [ -a "$webroot/$customWebpath/index.php" ]
	then
		timeDate=$(date +"%Y%m%d%H%M")
		mv "$webroot/$customWebpath/index.php" "$webroot/$customWebpath/index_$timeDate.php"

		printf "\e[31m%s %s%s" "Es wurde die Datei" "$webroot/$customWebpath" "/index.php gefunden!"
		printf "\n\e[31m%s" "Diese wurde, um die Installation von Pi Control zu ermoeglichen, umbenannt."
	fi

	printf "\n"
}

function configureCustomPort () {
	printf "\e[93m%s \e[0m" "Bitte gebe einen gueltigen Port zwischen 1 und 65535 an (Standard fuer Pi Control: 1693):"
        read customPort < /dev/tty
	
	while ! [[ "$customPort" -ge 1 && "$customPort" -le 65535 ]]
	do
		printf "\e[31m%s\n\e[93m%s \e[0m" "Leider ist der angegebene Port ungueltig." "Bitte gebe einen neuen Port an:"
		read customPort < /dev/tty
	done

	checkCustomPort
}

function checkCustomPort () {
	printf "\e[96m%s " "Pruefe Port..."
	
	#lsof -P -i :$customPort
	if [ "$(netstat -lnt | grep :$customPort)" == "" ]
	then
		printf "\e[32m%s\n" "Verfuegbar"
	else
		printf "\e[31m%s\n\e[93m%s \e[0m" "Vergeben! Der ausgewaehlte Port ist bereits von mindestens einem anderen Dienst in Benutzung." "Dennoch fortfahren? [j/n]"
		read answer < /dev/tty

		if ! [[ "$answer" == "j" || "$answer" == "J" || "$answer" == "y" || "$answer" == "Y" ]]
		then
			configureCustomPort
		fi
	fi
}

function downloadPiControl () {
	statusCode=$(cd /tmp && rm -f Pi-Control-latest.zip && curl -O -J -L "https://pi-control.de/service/v1/bash_installer/?download=latest" -s -o /dev/null -w "%{http_code}")
	
	if [ "$statusCode" = "200" ]; then
		printf "\e[32m%s\n" "Abgeschlossen"
	else
		printf "\e[31m%s %s\e[0m\n" "Fehler! Statuscode:" "$statusCode"
		printf "\e[31m%s\e[0m\n" "Bitte versuche es noch einmal oder kontaktiere mich. Ich werde dir so schnell wie moeglich weiterhelfen."
		exit 1;
	fi
}

function unzipPiControl () {
	printf "\e[0m"

	unzip -q -o /tmp/Pi-Control-latest.zip -d "$webroot/$customWebpath" && printf "\n\e[32m%s\n" "Abgeschlossen" || exit 1
}

function setPermissions () {
	printf "\n\e[93m%s%s%s\n%s \e[0m" "Es werden Benutzer + Gruppe fuer " $webroot/$customWebpath " auf www-data geaendert!" "Fortfahren? [j/n]"
	read answer < /dev/tty

	if [[ "$answer" == "j" || "$answer" == "J" || "$answer" == "y" || "$answer" == "Y" ]]
	then
		chown -R www-data:www-data "/$webroot/$customWebpath"
		find "/$webroot/$customWebpath" -type f -exec chmod 644 {} +
		find "/$webroot/$customWebpath" -type d -exec chmod 755 {} +

		printf "\e[32m%s\n" "Abgeschlossen"
	fi
}

function restartServices () {
	sleep 2
	
	if [ "$webserver" == "Apache2" ]
	then
		/etc/init.d/apache2 restart && printf "\n\e[32m%s\n" "Apache2 wurde erfolgreich neu gestartet."
	fi
	
	if [[ "$webserver" == "nothing" || "$webserver" == "Nginx" ]]
	then
		/etc/init.d/nginx restart && printf "\n\e[32m%s\n" "Nginx wurde erfolgreich neu gestartet."
	fi
	
	if [ "$webserver" == "Lighttpd" ]
	then
		/etc/init.d/lighttpd restart && printf "\n\e[32m%s\n" "Lighttpd wurde erfolgreich neu gestartet."
	fi
	
	if [ "$phpVersion" == "5" ]
	then
		if [ "$(command -v php5-fpm)" != "" ]
		then
			/etc/init.d/php5-fpm restart && printf "\n\e[32m%s\n" "PHP5-FPM wurde erfolgreich neu gestartet."
		fi
	fi
	
	if [ "$phpVersion" == "7" ]
	then
		if [ "$(command -v '${phpPrefix}'-fpm)" != "" ]
		then
			eval /etc/init.d/${phpPrefix}-fpm restart && printf "\n\e[32m%s\n" "${phpPrefix}-FPM wurde erfolgreich neu gestartet."
		fi
	fi
}

# Start program
clear

# Make terminal blue
printf "\e[96m"

printf "+----------------------------------------------+\n"
printf "|  ____  _    ____            _             _  |\n"
printf "| |  _ \(_)  / ___|___  _ __ | |_ _ __ ___ | | |\n"
printf "| | |_) | | | |   / _ \| '_ \| __| '__/ _ \| | |\n"
printf "| |  __/| | | |__| (_) | | | | |_| | | (_) | | |\n"
printf "| |_|   |_|  \____\___/|_| |_|\__|_|  \___/|_| |\n"
printf "|                                              |\n"
printf "|                                              |\n"
printf "|   Willkommen zum Download von Pi Control!    |\n"
printf "|                                              |\n"
printf "|        ------------------------------        |\n"
printf "|                                              |\n"
printf "| Installerversion: 1.1                        |\n"
printf "|                                              |\n"
printf "| Weitere Informationen zu Pi Control findest  |\n"
printf "| du auf meinem Blog: \e[93mhttps://willy-tech.de\e[96m    |\n"
printf "|                                              |\n"
printf "| Oder auf der offiziellen Pi Control Seite:   |\n"
printf "| \e[93mhttps://pi-control.de\e[96m                        |\n"
printf "|                                              |\n"
printf "| Bei Fragen oder Problemen schreib mir eine   |\n"
printf "| E-Mail: \e[93msupport@pi-control.de\e[96m                |\n"
printf "|                                              |\n"
printf "+----------------------------------------------+\n\n"

# Check for root/sudo
if [ "$(whoami)" != "root" ]
then
	printf "\e[31m%s\n%s\e[0m\n" "Du hast nicht ausreichend Berechtigungen, um mit der Installation fortzufahren." "Bitte wiederhole den Vorgang mit Root (sudo) Rechten!"
	exit 1
fi

# Disclaimer
printf "\e[96m%s\n%s\n%s\n%s\n%s\n\n\e[93m%s\e[0m " \
	"Beachte: Diese Shell-Skript nimmt eventuell Aenderungen am System vor, indem Pakete installiert," \
	"aktualisiert, bearbeitet oder geloescht werden. Neue Dateien werden hinzugefuegt und moeglicherweise" \
	"bereits vorhandene Dateien ueberschrieben. Berechtigungen von Dateien und Ordnern koennten geaendert werden." \
	"Die Ausfuehrung des Skript erfolgt auf eigene Verantwortung." \
	"Dieses Skript wurde mit groesster Sorgfalt zur Sicherheit und Richtigkeit erstellt!" \
	"Mit der Installation fortfahren? [j/n]"
read answer < /dev/tty

if ! [[ "$answer" == "j" || "$answer" == "J" || "$answer" == "y" || "$answer" == "Y" ]]
then
	exit 1
fi

# Check system update/upgrade
printf "\n\e[93m%s \e[0m" "System aktualisieren? (apt-get [update|upgrade|autoremove]) [j/n]"
read answer < /dev/tty

if [[ "$answer" == "j" || "$answer" == "J" || "$answer" == "y" || "$answer" == "Y" ]]
then
	printf "\e[32m%s\e[0m\n" "Aktualisiere System..."
	sleep 1
	apt-get -qy update && apt-get -qy upgrade && apt-get autoremove -qy && printf "\n\e[32mDas System wurde erfolgreich aktualisiert.\n"
fi

printf "\e[96m%s " "Pruefe Distribution..."

getDistribution
getDistributionCode

checkDistribution
if [ "$?" -eq "0" ]
then
	printf "\e[32m%s%s %s%s\e[0m\n" "Kompatibel (" "$distribution" "$distributionCode" ")"
else
	printf "\e[31m%s%s %s%s\e[0m\n" "Inkompatibel (" "$distribution" "$distributionCode" ")"

	printf "\e[93m%s \e[0m" "Dennoch fortfahren? (nicht empfohlen) [j/n]"
	read answer < /dev/tty

	if ! [[ "$answer" == "j" || "$answer" == "J" || "$answer" == "y" || "$answer" == "Y" ]]
	then
		exit 1
	fi
fi

printf "\e[96m%s " "Pruefe cURL..."

if [ "$(command -v curl)" != "" ]
then
	printf "\e[32m%s\n" "Vorhanden"
else
	printf "\e[31m%s\e[0m\n" "Nicht vorhanden! Wird installiert..."
	sleep 1
	apt-get -qy install curl && printf "\n\e[32m%s\n" "Das Paket wurde erfolgreich installiert."
fi

printf "\e[96m%s " "Pruefe Aktualisierung Tool..."

if [[ "$(curl -X GET -L -s "https://pi-control.de/service/v1/bash_installer/?info=versionCodeInstaller")" -le INSTALLER_VERSIONCODE ]]
then
	printf "\e[32m%s\n" "Aktuell"
else
	printf "\e[31m%s\n" "Veraltet! Lade neue Version..."
	sleep 1
	curl https://pi-control.de/pic_installer | sudo bash
	exit 1
fi

printf "\e[96m%s " "Pruefe Unzip..."

if [ "$(command -v unzip)" != "" ]
then
	printf "\e[32m%s\n" "Vorhanden"
else
	printf "\e[31m%s\e[0m\n" "Nicht vorhanden! Wird installiert..."
	sleep 1
	apt-get -qy install unzip && printf "\n\e[32m%s\n" "Das Paket wurde erfolgreich installiert."
fi

printf "\e[96m%s " "Pruefe Webserver..."

getWebserver

installWebserver

printf "\e[96m%s " "Pruefe Webverzeichnis..."

checkWebroot

printf "\e[96m%s " "Pruefe PHP..."

installPHP

printf "\e[96m%s " "Pruefe Konfiguration Webserver..."

configureWebserver

printf "\e[96m%s " "Lade neuste Version von Pi Control herunter..."

downloadPiControl

printf "\e[96m%s " "Entpacke Pi Control..."

unzipPiControl

printf "\e[96m%s " "Pruefe Berechtigungen..."

setPermissions

printf "\e[96m%s\n\e[0m" "Starte Dienste neu..."

restartServices

printf "\n\e[32m%s\e[0m\n" "Du kannst nun mit der abschließenden Installation im Browser fortfahren."
printf "\e[32m%s \e[93m%s\e[32m oder \e[93m%s\e[0m\n" "Im Browser findest du Pi Control unter" "http://$ipaddress/$customWebpath" "http://$hostname/$customWebpath"

printf "\n"