#!/bin/bash

### Script für eine vollständige Installation der Notfallbox
### Xpi
###
### 116		Aus dem Setup wurde die Nachinstallation aller Hilfsprogramme ins Installationsprogramm übernommen.
### 115		Die Rechte für www-data haben nicht ausgereicht für gpio-Operationen ==> erweitert
### 114		Das Tool nc (netcat) wird nicht standard-mässig installiert, ist aber für CITADEL notwendig.
### 113		Fehlerkorrektur für Xpc
### 112		Fehlende Verzeichnisrechte für /home/notfallbox verhindern Filetransfer
###	111		Möglichkeit zur NICHT-Inbetriebnahme des WAP bei der Installation
###	110		Da die Notfallbox S nicht mehr existiert, wurde die Installation der Xpi auf allen Modellen ab 02W eingepflegt.
### 109		Die Notfallbox S wurde entfernt (wird nicht mehr gepflegt), ebenso monsta, da dieses im Paket enthalten ist
### 108		Kiwix-Server-Dateien werden gelöscht, da nicht mehr gebraucht nach der Installation
### 107		IF-Abfragen für befehle ergänzt
### 106		iw kann auf debian 12 nur mit sudo ausgeführt werden
### 105		Wenn der Installations-Computer eine ARM-CPU hat, wird das Model Xpc nicht mehr angeboten
### 104		Globale Umgebungsvariablen nfbSetup, nfbUpdate, nfbSetup wird gesetzt
### 1.13	Globale Umgebungsvariable nfbModel wird mit dem Notfallbox-Model gesetzt
### 1.12	Installation des Update-Programms unter /usr/bin
### 1.11	Anpassungen für Xpc
###	1.00	Erste Setup
###			Übernahme von V1
script="116"

inc_Model_M() {
	nfbModel="M"
	nfbVersion=116
	nfbUpdate=103
	nfbSetup=103
	dlPath="https://login.yoursecurecloud.de/f/ab621f67ff3a46f6a4ce/?dl=1"
	nfbArchiv="NFB-$nfbModel-$nfbVersion.zip"
}
inc_Model_Xpc() {
	nfbModel="Xpc"
	nfbVersion=140
	nfbUpdate=107
	nfbSetup=116
	dlPath="https://login.yoursecurecloud.de/f/1651d982633d4b40821e/?dl=1"
	nfbArchiv="NFB-$nfbModel-$nfbVersion.zip"
}
inc_Model_Xpi() {
	nfbModel="Xpi"
	nfbVersion=140
	nfbUpdate=107
	nfbSetup=116
	dlPath="https://login.yoursecurecloud.de/f/0f95a2b4bcef4606a7db/?dl=1"
	nfbArchiv="NFB-$nfbModel-$nfbVersion.zip"
}

### Definitionen
N='\033[0;39m'
B='\033[1;34m'
Y='\033[1;33m'
R='\033[0;31m'
modVer="$nfbModel.$nfbSetup"
header="### Installation Notfallbox ($script) ###"
webRoot="/var/www/html"
downloadRoot="$webRoot/download"
kiwixRoot="$webRoot/kiwix"
temp="tempG"
downloadfilename="NFB-$modVer.ZIP"
tempfilename="$temp/$downloadfilename"
konfigFile=".notfallbox_config"
statusFile=".notfallbox_status"
installLogfile="Installation_Logfile_Notfallbox"
debian=`cat /etc/debian_version|cut -d '.' -f 1`

   wifiAuswahlM=("01" "PI Zero       WiFi: USB")
  wifiAuswahlM+=("02" "PI Zero W     WiFi: intern")
  wifiAuswahlM+=("03" "PI Zero W     WiFi: USB")
  wifiAuswahlM+=("04" "PI Zero 2W    WiFi: intern")
  wifiAuswahlM+=("05" "PI Zero 2W    WiFi: USB")
  wifiAuswahlM+=("06" "PI 3          WiFi: intern")
  wifiAuswahlM+=("07" "PI 3          WiFi: USB")
  wifiAuswahlM+=("08" "PI 4          WiFi: intern")
  wifiAuswahlM+=("09" "PI 4          WiFi: USB")
  wifiAuswahlM+=("10" "PI 5          WiFi: intern")
  wifiAuswahlM+=("11" "PI 5          WiFi: USB")

 wifiAuswahlXpi=("12" "PI Zero 2W    WiFi: intern")
wifiAuswahlXpi+=("13" "PI Zero 2W    WiFi: USB")
wifiAuswahlXpi+=("14" "PI Zero 2W    WiFi: nein (Server-Modus)")
wifiAuswahlXpi+=("15" "PI 3          WiFi: intern")
wifiAuswahlXpi+=("16" "PI 3          WiFi: USB")
wifiAuswahlXpi+=("17" "PI 3          WiFi: nein (Server-Modus)")
wifiAuswahlXpi+=("18" "PI 4          WiFi: intern")
wifiAuswahlXpi+=("19" "PI 4          WiFi: USB")
wifiAuswahlXpi+=("20" "PI 4          WiFi: nein (Server-Modus)")
wifiAuswahlXpi+=("21" "PI 5          WiFi: intern")
wifiAuswahlXpi+=("22" "PI 5          WiFi: USB")
wifiAuswahlXpi+=("23" "PI 5          WiFi: nein (Server-Modus)")

 wifiAuswahlXpc=("24" "WiFi: intern")
wifiAuswahlXpc+=("25" "WiFi: USB")
wifiAuswahlXpc+=("26" "WiFi: nein (Server Modus)")

############## FUNKTIONEN ############## FUNKTIONEN ############## FUNKTIONEN ############## FUNKTIONEN ############## FUNKTIONEN ############## FUNKTIONEN ##############
# Splash-Screen
menu() {
	echo "debian,$debian" >> $konfigFile
	echo -e "\n Einen Moment bitte. Wir müssen die Datenbank des Betriebssystems aktualisieren, bevor es los geht."
	echo "### Update der Debian-Sourcen"  >> $installLogfile 2>&1
	sudo apt -y -qqqq update >> $installLogfile 2>&1
	unset aptListe
	if [ ! -f "/usr/sbin/iw" ]; then
		aptListe+="iw "
	fi
	if [ ! -f "/usr/bin/dialog" ]; then
		aptListe+="dialog "
	fi
	if [ ! -f "/usr/bin/unzip" ]; then
		aptListe+="unzip "
	fi
	if [ ! -f "/usr/bin/ftp" ]; then
		aptListe+="ftp "
	fi
	if [ ! -f "/usr/bin/nc" ]; then
		aptListe+="netcat-* "
	fi
	if [ ! -f "/usr/sbin/iw" ]; then
		aptListe+="iw "
	fi
	if [ ! -f "/usr/bin/xmlstarlet" ]; then
		aptListe+="xmlstarlet "
	fi
	if [ ! -f "/usr/bin/dialog" ]; then
		aptListe+="dialog "
	fi
	if [ ! -f "/usr/sbin/if" ]; then
		aptListe+="net-tools "
	fi
	if [ ! -z "$aptListe" ]; then
		echo -ne "\n$Y Einen Moment bitte. Aktuell fehlende Hilfsprogramme werden nachinstalliert.\n"
		sudo apt -qqqqqqqq -y install $aptListe > /dev/null 2>&1
	fi

	### Das Startmenü
	infoText+="Die Installation besteht aus folgenden Teilen:\n"
	infoText+="----------------------------------------------\n"
	infoText+="    a) Auswahl der Installationsoptionen\n"
	infoText+="    b) Betriebssystem: Installation zusätzlicher Programme, Konfiguration\n"
	infoText+="    c) Einrichtung des WLAN-Hotspots (wenn gewünscht)\n"
	infoText+="    d) Installation der Systemdienste\n"
	infoText+="    e) Installation der eigentlichen Notfallbox-Anwendung\n"
	infoText+="\n"
	infoText+="Nach Abschluss aller Schritte erhält man eine betriebsfertige Notfallbox in der Grundausstattung\n\n"
	infoText+="Sollen wir loslegen?"
	if ! whiptail --clear --yes-button "Let's Rock'n'Roll" --no-button "Lieber doch nicht!" --backtitle "$header" --title "Herzlich Willkommen !!!" --yesno "$infoText" 0 100; then
		#clear
		echo -e "$R\nDie Installation wurde abgebrochen.\n$N"
		exit
	fi

	cpuModel=`lscpu | awk '/Vendor ID:/{print $3}'`
	unset cfgModelChoice
	if [ "$cpuModel" = "ARM" ]; then
		cfgModelChoice+=("M" 	"Mini - geeignet für ALLE PI-Modelle")
		cfgModelChoice+=("Xpi" 	"eXtra PI - geeignet für PI 02W/3/4/5")
	else
		cfgModelChoice+=("Xpc" 	"eXtra PC - geeignet für Intel/AMD PC (x86_64)")
	fi
	cfgModelText="Bitte verrate uns, welche Veriante der Notfallbox Du installieren willst.";
	if [ "$debian" -ge 12 ]; then
		cfgModel=`whiptail --nocancel --clear --backtitle "$header" --title "a) Installationsoptionen" --menu "$cfgModelText" 13 100 0 "${cfgModelChoice[@]}" 3>&1 1>&2 2>&3`
	else
		cfgModel=`dialog --backtitle "$header" --title "a) Installationsoptionen" --menu "$cfgModel" "${cfgModelChoice[@]}" 3>&1 1>&2 2>&3`
	fi
	echo "### Auswahl Model: $cfgModel ###"  >> $installLogfile 2>&1
	echo -n "model," >> $konfigFile;
	echo $cfgModel >> $konfigFile;
	case $cfgModel in
		"M")	inc_Model_M;;
		"Xpi")	inc_Model_Xpi;;
		"Xpc")	inc_Model_Xpc;;
	esac
	echo "### Auswahl Downloadpfad: $dlPath ###"  >> $installLogfile 2>&1
	echo "dlPath,$dlPath" >> $konfigFile;
	echo "### Auswahl Software-Setup: $nfbSetup ###"  >> $installLogfile 2>&1
	echo "version,$nfbSetup" >> $konfigFile;

	# Whiptail hat in Debian kleiner 12 einen Bug, daher wird hier umgeschalten zwischen Whiptail und dialog
	debian=`cat /etc/debian_version|cut -d '.' -f 1`
	 cfgExtWifi="\nBitte verrate uns, welche Art von Hardware Du betreibst (Computer und WLAN/WiFi).\n"
	cfgExtWifi+="Es werden nur diejenigen Geräte angezeigt, welche zur von Dir gewählten Notfallbox-Variante passen.";
	if [ $debian -ge 12 ]; then
		case $cfgModel in
			"M")	wifi=`whiptail --nocancel --clear --backtitle "$header" --title "a) Installationsoptionen" --menu "$cfgExtWifi" 0 100 0 "${wifiAuswahlM[@]}" 3>&1 1>&2 2>&3`;;
			"Xpi")	wifi=`whiptail --nocancel --clear --backtitle "$header" --title "a) Installationsoptionen" --menu "$cfgExtWifi" 0 100 0 "${wifiAuswahlXpi[@]}" 3>&1 1>&2 2>&3`;;
			"Xpc")	wifi=`whiptail --nocancel --clear --backtitle "$header" --title "a) Installationsoptionen" --menu "$cfgExtWifi" 0 100 0 "${wifiAuswahlXpc[@]}" 3>&1 1>&2 2>&3`;;
		esac
	else
		case $cfgModel in
			"M") 	wifi=`dialog --backtitle "$header" --title "a) Installationsoptionen" --menu "$cfgExtWifi" 0 100 0 "${wifiAuswahlM[@]}" 3>&1 1>&2 2>&3`;;
			"Xpi") 	wifi=`dialog --backtitle "$header" --title "a) Installationsoptionen" --menu "$cfgExtWifi" 0 100 0 "${wifiAuswahlXpi[@]}" 3>&1 1>&2 2>&3`;;
			"Xpc") 	wifi=`dialog --backtitle "$header" --title "a) Installationsoptionen" --menu "$cfgExtWifi" 0 100 0 "${wifiAuswahlXpc[@]}" 3>&1 1>&2 2>&3`;;
		esac
	fi
	wifiDevice=`ip a | grep wl | cut -d " " -f2 | cut -d ":" -f1`
	case $wifi in
		"01")	svcWifi="usb"; echo "svcWifi,usb" >> $konfigFile; echo "pi,0,$wifiDevice" >> $konfigFile;;
		"02") 	svcWifi="internal"; echo "svcWifi,internal" >> $konfigFile; echo "pi,0w,$wifiDevice" >> $konfigFile;;
		"03")	svcWifi="usb"; echo "svcWifi,usb" >> $konfigFile; echo "pi,0w,$wifiDevice" >> $konfigFile;;
		"04") 	svcWifi="internal"; echo "svcWifi,internal" >> $konfigFile; echo "pi,02w,$wifiDevice" >> $konfigFile;;
		"05")	svcWifi="usb"; echo "svcWifi,usb" >> $konfigFile; echo "pi,02w,$wifiDevice" >> $konfigFile;;
		"06") 	svcWifi="internal"; echo "svcWifi,internal" >> $konfigFile; echo "pi,3,$wifiDevice" >> $konfigFile;;
		"07")	svcWifi="usb"; echo "svcWifi,usb" >> $konfigFile; echo "pi,3,$wifiDevice" >> $konfigFile;;
		"08") 	svcWifi="internal"; echo "svcWifi,internal" >> $konfigFile; echo "pi,4,$wifiDevice" >> $konfigFile;;
		"09")	svcWifi="usb"; echo "svcWifi,usb" >> $konfigFile; echo "pi,4,$wifiDevice" >> $konfigFile;;
		"10")	svcWifi="internal"; echo "svcWifi,internal" >> $konfigFile; echo "pi,5,$wifiDevice" >> $konfigFile;;
		"11")	svcWifi="usb"; echo "svcWifi,usb" >> $konfigFile; echo "pi,5,$wifiDevice" >> $konfigFile;;
		"12")	svcWifi="internal"; echo "svcWifi,internal" >> $konfigFile; echo "pi,02w,$wifiDevice" >> $konfigFile;;
		"13")	svcWifi="usb"; echo "svcWifi,usb" >> $konfigFile; echo "pi,02w,$wifiDevice" >> $konfigFile;;
		"14")	svcWifi="no"; echo "svcWifi,no" >> $konfigFile; echo "pi,02w,no" >> $konfigFile;;
		"15")	svcWifi="internal"; echo "svcWifi,internal" >> $konfigFile; echo "pi,3,$wifiDevice" >> $konfigFile;;
		"16")	svcWifi="usb"; echo "svcWifi,usb" >> $konfigFile; echo "pi,3,$wifiDevice" >> $konfigFile;;
		"17")	svcWifi="no"; echo "svcWifi,no" >> $konfigFile; echo "pi,3,no" >> $konfigFile;;
		"18")	svcWifi="internal"; echo "svcWifi,internal" >> $konfigFile; echo "pi,4,$wifiDevice" >> $konfigFile;;
		"19")	svcWifi="usb"; echo "svcWifi,usb" >> $konfigFile; echo "pi,4,$wifiDevice" >> $konfigFile;;
		"20")	svcWifi="no"; echo "svcWifi,no" >> $konfigFile; echo "pi,4,no" >> $konfigFile;;
		"21")	svcWifi="internal"; echo "svcWifi,internal" >> $konfigFile; echo "pi,5,$wifiDevice" >> $konfigFile;;
		"22")	svcWifi="usb"; echo "svcWifi,usb" >> $konfigFile; echo "pi,5,$wifiDevice" >> $konfigFile;;
		"23")	svcWifi="no"; echo "svcWifi,no" >> $konfigFile; echo "pi,5,no" >> $konfigFile;;
		"24")	svcWifi="internal"; echo "svcWifi,internal" >> $konfigFile; echo "pc,0,$wifiDevice" >> $konfigFile;;
		"25")	svcWifi="usb"; echo "svcWifi,usb" >> $konfigFile; echo "pc,0,$wifiDevice" >> $konfigFile;;
		"25")	svcWifi="no"; echo "svcWifi,no" >> $konfigFile; echo "pc,0,no" >> $konfigFile;;
	esac

	# Abfrage ob die Installation begonnen werden kann
 	cfgFinText="Jetzt werden die notwendigen Dateien heruntergeladen, platziert und installiert. Dies wird - abhängig vom verwendeten Raspberry PI / Computer ein wenig dauern.\n\n"
	cfgFinText+="Willst Du nun die Installation starten?"
	if ! whiptail --clear --yes-button "Yes, hau' rein!" --no-button "STOP! Besser doch nicht!" --backtitle "$header" --title "Installation" --yesno "$cfgFinText" 11 100; then
		#clear
		echo -e "$R\nDie Installation wurde ohne Änderungen am System abgebrochen.\nZum erneuten Aufruf bitte $0 erneut starten.\n$N"
		exit
	fi
	echo "1" > $statusFile
}

# Einlesen der gespeicherten Konfiguration nach Reboot
readConfig() {
	TERM=ansi whiptail --backtitle "$header" --title "a) Installationsoptionen" --infobox "Die erstellte Konfiguration wird eingelesen.\n\nEinen Moment bitte." 9 0
	IFS=","
	declare -A -g konf
	while read -a datei; do
  			konf["${datei[0]}"]="${datei[1]}"
	done < $konfigFile
}

# Konfiguration über raspi-config (nur Raspberry PI
inst1() {
	if [ "$cfgModel" != "Xpc" ]; then
		TERM=ansi whiptail --backtitle "$header" --title "b) Betriebssystem" --infobox "Das Betriebssystem wird angepasst.\n\nEinen Moment bitte." 9 0
		echo "### Raspi-Config: do_change_locale de_DE.UTF-8 UTF-8 ###"  >> $installLogfile 2>&1
		sudo raspi-config nonint do_change_locale de_DE.UTF-8 UTF-8  >> $installLogfile 2>&1
		echo "### Raspi-Config: do_wifi_country DE ###"  >> $installLogfile 2>&1
		sudo raspi-config nonint do_wifi_country DE  >> $installLogfile 2>&1
		echo "### Raspi-Config: do_expand_rootfs ###"  >> $installLogfile 2>&1
		sudo raspi-config nonint do_expand_rootfs  >> $installLogfile 2>&1
	fi
	echo "2" > $statusFile
}

# Interner WiFi-Chip oder USB-Wifi-Dongle (nur Raspberry PI)
inst2() {
	if [ "$cfgModel" != "Xpc" ]; then
		TERM=ansi whiptail --backtitle "$header" --title "c) WLAN-Hotspot (WAP)" --infobox "Der Hotspot wird installiert und eingerichtet.\n\nEinen Moment bitte" 9 0
		if [ "${konf["pi"]}"  = "0" ]; then
			if [ -f "/boot/firmware/config.txt" ]; then
				configTXT="/boot/firmware/config.txt"
			else
				configTXT="/boot/config.txt"
			fi
			sudo tee -a $configTXT <<EOF
### Bluetooth abschalten
dtoverlay=disable-bt
EOF
			wapText="Ein Neustart ist erforderlich\n"
			wapText+="Bitte nach dem Neustart wieder ./$0 aufrufen.\n"
			wapText+="\nACHTUNG: Bitte den EXTERNEN USB-WiFI-Dongle einstecken!\n"
			whiptail --backtitle "$header" --title "c) WLAN-Hotspot (WAP)" --msgbox "$wapText" 0 0
			echo "3" > $statusFile;
			sudo reboot
		else
			if [ "${konf["svcWifi"]}" = "usb" ]; then
				if [ -f "/boot/firmware/config.txt" ]; then
					configTXT="/boot/firmware/config.txt"
				else
					configTXT="/boot/config.txt"
				fi
				sudo tee -a $configTXT <<EOF
### Internen WLAN-Chip abschalten (z.B. Pi Zero W / Zero 2 W / 3 / 4 / 5)
dtoverlay=disable-wifi
### Bluetooth abschalten
dtoverlay=disable-bt
EOF
			elif [ "${konf["svcWifi"]}" = "internal" ]; then
				if [ -f "/boot/firmware/config.txt" ]; then
					configTXT="/boot/firmware/config.txt"
				else
					configTXT="/boot/config.txt"
				fi
				sudo tee -a $configTXT <<EOF
### Bluetooth abschalten
dtoverlay=disable-bt
EOF
			fi
			wapText="Ein Neustart ist erforderlich\n"
			wapText+="Bitte nach dem Neustart wieder ./$0 aufrufen.\n"
			if [ "${konf["svcWifi"]}" = "usb" ]; then
				wapText+="\nACHTUNG: Bitte den EXTERNEN USB-WiFI-Dongle einstecken!\n"
			fi
			whiptail --backtitle "$header" --title "c) WLAN-Hotspot (WAP)" --msgbox "$wapText" 0 0
			echo "3" > $statusFile;
			sudo reboot
		fi
	else
		wapText="Ein Neustart ist erforderlich\n"
		wapText+="Bitte nach dem Neustart wieder $0 aufrufen.\n"
		if [ "${konf["svcWifi"]}" = "usb" ]; then
			wapText+="\nACHTUNG: Bitte den EXTERNEN USB-WiFI-Dongle einstecken!\n"
		fi
		whiptail --backtitle "$header" --title "c) WLAN-Hotspot (WAP)" --msgbox "$wapText" 0 0
		echo "3" > $statusFile;
		sudo reboot
	fi
	echo "3" > $statusFile;

}

# Installation WAP
inst3() {
	wifiDevice=`sudo iw dev | grep -oP "Interface \K.+"`
	sudo iw dev $wifiDevice set power_save off >> $installLogfile 2>&1
	TERM=ansi whiptail --backtitle "$header" --title "c) WLAN-Hotspot (WAP)" --infobox "Der Hotspot wird installiert und eingerichtet.\n\nEinen Moment bitte" 9 0
	ssid="Notfallbox-"
	ssid+=`od -An -tx -N4 /dev/random | cut -d ' ' -f2`
	sudo apt -y install network-manager >> $installLogfile 2>&1
	echo "### Hotspot per nmcli wird erstellt" >> $installLogfile 2>&1
    sudo nmcli con add con-name hotspot ifname $wifiDevice type wifi ssid "$ssid"  >> $installLogfile 2>&1
	sudo nmcli con mod hotspot 802-11-wireless.mode ap 802-11-wireless.band bg >> $installLogfile 2>&1
	sudo nmcli con mod hotspot ipv4.addresses 10.0.0.1/8 >> $installLogfile 2>&1
	sudo nmcli con mod hotspot ipv4.gateway 10.0.0.1 >> $installLogfile 2>&1
	sudo nmcli con mod hotspot ipv4.method manual >> $installLogfile 2>&1
	sudo nmcli con mod hotspot ipv4.method shared >> $installLogfile 2>&1
	sudo nmcli con mod hotspot connection.autoconnect yes >> $installLogfile 2>&1
	sudo nmcli con up hotspot >> $installLogfile 2>&1
	echo "4" > $statusFile;
}

func_install_M() {
	echo "### Webserver lighttpd" >> $installLogfile 2>&1
	sudo apt -qqqq -y install lighttpd php-cgi >> $installLogfile 2>&1
	sudo lighttpd-enable-mod fastcgi fastcgi-php >> $installLogfile 2>&1
	sudo service lighttpd force-reload > /dev/null >> $installLogfile 2>&1
	sudo apt install -y openssl shellinabox  >> $installLogfile 2>&1
	sudo sed -i "s|SHELLINABOX_PORT=4200|SHELLINABOX_PORT=666|g" /etc/default/shellinabox  >> $installLogfile 2>&1
	sudo systemctl restart shellinabox >> $installLogfile 2>&1
}

func_install_Xpi() {
	echo "### Webserver apache2" >> $installLogfile 2>&1
	sudo debconf-set-selections <<< "phpmyadmin phpmyadmin/reconfigure-webserver multiselect apache2"
	sudo debconf-set-selections <<< "phpmyadmin phpmyadmin/dbconfig-install boolean true"
	sudo debconf-set-selections <<< "phpmyadmin phpmyadmin/mysql/admin-user string root"
	sudo debconf-set-selections <<< "phpmyadmin phpmyadmin/mysql/admin-pass password notfallbox"
	sudo debconf-set-selections <<< "phpmyadmin phpmyadmin/mysql/app-pass password notfallbox"
	sudo debconf-set-selections <<< "phpmyadmin phpmyadmin/app-password-confirm password notfallbox"
	sudo apt -qqqq -y install apache2 php php-mysql mariadb-server mariadb-client phpmyadmin >> $installLogfile 2>&1
	sudo mysql -sfu root <<EOS
ALTER USER 'root'@'localhost' IDENTIFIED BY 'notfallbox';
DELETE FROM mysql.user WHERE User='';
DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');
DROP DATABASE IF EXISTS test;
DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%';
FLUSH PRIVILEGES;
EOS
	sudo sudo mariadb -u root -pnotfallbox <<EOS >> $installLogfile 2>&1
CREATE USER 'notfallbox'@'localhost' IDENTIFIED BY 'notfallbox';
GRANT ALL PRIVILEGES ON notfallbox . * TO 'notfallbox'@'localhost';
GRANT ALL PRIVILEGES ON *.* TO 'phpmyadmin'@'localhost';
FLUSH PRIVILEGES;
EOS
	sudo apt -y install openssl shellinabox >> $installLogfile 2>&1
	sudo sed -i "s|SHELLINABOX_PORT=4200|SHELLINABOX_PORT=666|g" /etc/default/shellinabox  >> $installLogfile 2>&1
	sudo systemctl restart shellinabox >> $installLogfile 2>&1
	sudo apt -y install proftpd >> $installLogfile 2>&1
	sudo mkdir /home/ftp
	echo notfallbox | sudo ftpasswd --name notfallbox --gid 33 --uid 33 --home /home/ftp --shell /bin/false --passwd --stdin  >> $installLogfile 2>&1
}

# Der Webserver wird installiert
inst4() {
	TERM=ansi whiptail --backtitle "$header" --title "d) Webserver" --infobox "Der Webserver wird betriebsbereit installiert.\n\nEinen Moment bitte" 9 0
	case ${konf["model"]} in
		"M")	func_install_M;;
		"Xpi")	func_install_Xpi;;
		"Xpc")	func_install_Xpi;;
	esac
	echo "5" > $statusFile
}

# Die Inhalte des Webservers werden heruntergeladen und installiert
inst5() {
	case ${konf["model"]} in
		"M")	inc_Model_M;;
		"Xpi")	inc_Model_Xpi;;
		"Xpc")	inc_Model_Xpi;;
	esac
	# Temp-Verzeichnis anlegen
	TERM=ansi whiptail --backtitle "$header" --title "e) Inhalte" --infobox "Die Inhalte für den Webserver werden heruntergeladen und installiert.\n\nEinen Moment bitte." 9 0
	sleep 2
	if [ ! -d $temp ]; then
        	sudo mkdir $temp;
	fi
	# Datei vom Server holen
	if [ ! -f $nfbArchiv ]; then
        wget $dlPath -q --show-progress  -O $nfbArchiv >> $installLogfile 2>&1
	fi
	# Archiv entpacken
	if [ -f $nfbArchiv ]; then
        	sudo unzip -q $nfbArchiv -d $webRoot >> $installLogfile 2>&1
	else
			echo -e "$R Aus irgend einem Grund wurde das heruntergeladene Installationsarchiv nicht gefunden. Bitte prüfe das Verzeichnis $N $temp"
			return
	fi
	# Kiwix einrichten und starten
	if [ -f "$kiwixRoot/kiwix.service" ]; then
        	sudo cp $kiwixRoot/kiwix.service /etc/systemd/system >> $installLogfile 2>&1
			hw=$(uname -m)
			sudo cp $kiwixRoot/kiwix_$hw/* $kiwixRoot >> $installLogfile 2>&1
        	sudo systemctl enable kiwix.service >> $installLogfile 2>&1
        	sudo systemctl start kiwix.service >> $installLogfile 2>&1
        	sudo rm -r $kiwixRoot/kiwix_aarch64
        	sudo rm -r $kiwixRoot/kiwix_armhf
        	sudo rm -r $kiwixRoot/kiwix_armv6
        	sudo rm -r $kiwixRoot/kiwix_armv6l
        	sudo rm -r $kiwixRoot/kiwix_x86_64
	fi
	webRoot="/var/www/html"
	# Datenbank erstellen und Inhalte hineinziehen
	if [ ! "$nfbModel" = "M" ]; then
		echo "### Datenbank wird erstellt und eingelesen" >> $installLogfile 2>&1
		sudo mysql -uroot -pnotfallbox < $webRoot/notfallbox.sql >> $installLogfile 2>&1
		sudo rm $webRoot/notfallbox.sql >> $installLogfile 2>&1
	fi
	# Nacharbeiten
	if [ -f "$webRoot/index.php" ]; then
        	sudo chown www-data:www-data $webRoot/* -R
        	sudo chmod 777 $webRoot/* -R
        	if [ -f "$webRoot/index.html" ]; then
        		sudo rm $webRoot/index.html
        	elif [ -f "$webRoot/index.lighttpd.html" ]; then
        		sudo rm $webRoot/index.lighttpd.html
        	fi  
        	if [ -f "$nfbArchiv" ]; then
				sudo rm $nfbArchiv
			fi
	fi
	# Eine globale Umgebungsvariable mit dem Notfallbox-Modell wird gesetzt
	nfbModel=${konf["model"]}
	sudo echo "export nfbModel=$nfbModel" | sudo tee -a /etc/environment
	sudo echo "export nfbVersion=$nfbVersion" | sudo tee -a /etc/environment
	sudo echo "export nfbSetup=$nfbSetup" | sudo tee -a /etc/environment
	sudo echo "export nfbUpdate=$nfbUpdate" | sudo tee -a /etc/environment
	# Setup, Update und Version wird installiert
	sudo cp $webRoot/install/Setup /usr/bin >> $installLogfile 2>&1
	sudo cp $webRoot/install/Update /usr/bin >> $installLogfile 2>&1
	sudo cp $webRoot/install/Version /usr/bin >> $installLogfile 2>&1
	sudo chmod 555 /usr/bin/Setup >> $installLogfile 2>&1
	sudo chmod 555 /usr/bin/Update >> $installLogfile 2>&1
	sudo chmod 555 /usr/bin/Version >> $installLogfile 2>&1
	sudo ln -s /usr/bin/Setup /usr/bin/setup >> $installLogfile 2>&1
	sudo ln -s /usr/bin/Setup /usr/bin/nfbSetup >> $installLogfile 2>&1
	sudo ln -s /usr/bin/Setup /usr/bin/nfbsetup >> $installLogfile 2>&1
	sudo ln -s /usr/bin/Update /usr/bin/update >> $installLogfile 2>&1
	sudo ln -s /usr/bin/Update /usr/bin/nfbUpdate >> $installLogfile 2>&1
	sudo ln -s /usr/bin/Update /usr/bin/nfbupdate >> $installLogfile 2>&1
	sudo ln -s /usr/bin/Version /usr/bin/version >> $installLogfile 2>&1$dir = "/etc/php5/";
	sudo ln -s /usr/bin/Version /usr/bin/nfbVersion >> $installLogfile 2>&1
	sudo ln -s /usr/bin/Version /usr/bin/nfbversion >> $installLogfile 2>&1
	sudo rm -r $webRoot/install
	echo "E" > $statusFile
}

# Wird aufgerufen, wenn die Installation ein zweites Mal gestartet werden soll!
fehler() {
	 fehlerText="Unglaublich, aber wahr: Die Notfallbox wurde bereits vollständig installiert.\n"
	fehlerText+="Ein erneuter Installationsvorgang würde das System massiv beschädigen.\n\n"
	fehlerText+="Die Notfallbox wurde mit Standard-Einstellungen installiert.\nDiese kannst Du jederzeit über folgendes Kommando ändern:\n"
	fehlerText+="\n>>> Setup <<<"
	whiptail --clear --backtitle "$header" --title "INFORMATION" --msgbox "$fehlerText" 0 0
	echo "F" > $statusFile	fi

	#clear
	echo -e "$Y\nNichts passiert ;-)\n$N"
	exit
}

# Abschluss-Info
abschluss() {
	abschlussText="Die Installation der Notfallbox wurde vollständig beendet! \n\n"
	abschlussText+="Weitere Informationen zum System findest Du unter https://notfallbox.info \n"
	abschlussText+="Hilfe findest Du in unserem Helpdesk unter https://notfallbox.info/helpdesk \n\n"
	abschlussText+="Die Notfallbox wurde mit Standard-Einstellugnen installiert. Diese kannst Du jederzeit über folgendes Kommando ändern:\n"
	abschlussText+="Setup\n\n"
	abschlussText+="... und nun  können wir nur noch hoffen, dass das ganze System niemals ernsthaft zum Einsatz kommen muss. "
	abschlussText+="Es wäre zwar schade um die viele Arbeit - aber es muss ja nicht sein, dass wir in eine Katastrophe hineinschlittern, "
	abschlussText+="in welcher wir um den Einsatz von Notfallboxen nicht herumkommen.\n\n"
	abschlussText+="Beste Grüße und alles Gute wünscht Guido, DJ1NG, DN1NF, Manager von DL0JRK und DF0BJ"
	whiptail --clear --backtitle "$header" --title "INFORMATION" --msgbox "$abschlussText" 17 100
	echo "F" > $statusFile
	if [ -f "$konfigFile" ]; then
		sudo rm $konfigFile
	fi
	if [ -d "$temp" ]; then
		sudo rm -r $temp
	fi
	echo 'www-data ALL=(root) NOPASSWD: /sbin/reboot' | sudo EDITOR='tee -a' visudo
	echo 'www-data ALL=(root) NOPASSWD: /sbin/halt' | sudo EDITOR='tee -a' visudo
	echo 'www-data ALL=(root) NOPASSWD: /bin/systemctl' | sudo EDITOR='tee -a' visudo
	echo 'www-data ALL=(root) NOPASSWD: /var/www/html/gpio/dienst' | sudo EDITOR='tee -a' visudo
	echo 'www-data ALL=(root) NOPASSWD: /bin/sudo' | sudo EDITOR='tee -a' visudo
	clear
	echo -e "\nDie installation der Notfallbox ist beendet. Alles Gute!   \n"
	echo -e "Bitte nicht vergessen: Alle Einstellungen der Notfallbox lassen sich ändern mit dem Kommando:\n"
	echo -e "$Y Setup\n$N"
	if [ -f "$0" ]; then
		sudo rm $0
	fi
	if [ -f ".notfallbox_status" ]; then
		sudo rm .notfallbox_status
	fi
	sudo chmod 777 /home/ftp
	sudo chmod 777 /home/notfallbox
	echo -e "$R Die Notfallbox wird zum Abschluss noch einmal neu gestartet. $N\n"
	sudo reboot
}
################ INSTALLATION ################ INSTALLATION ################ INSTALLATION ################ INSTALLATION ################ INSTALLATION ################ INSTALLATION ################

if [ -f $statusFile ]; then
	status=`cat $statusFile`
fi
case $status in
	"F")		fehler;;
	"E")		abschluss;;
	"5")		readConfig; inst5; abschluss;;
	"4")		readConfig; inst4; inst5; abschluss;;
	"3")		readConfig; inst3; inst4; inst5; abschluss;;
	"2")		readConfig; inst2;;
	"1")		readConfig; inst1; inst2;;
	*)			if [ -f "$konfigFile" ]; then
					sudo rm "$konfigFile";
				fi
				if [ -f "$installLogfile" ]; then
					sudo rm $installLogfile
				fi
				menu; readConfig; inst1; inst2; inst3; inst4; inst5; abschluss;;
esac
