#!/bin/bash
if [ "$(id -u)" != "0" ]; then
	echo "This script must be run as root" 1>&2
	exit 1
fi

SCRIPTDIR="$( cd "$(dirname $0)" && pwd )"
export NCURSES_NO_UTF8_ACS=1

builddate="current"
if [[ -n $1 ]]; then
	builddate=$1
fi

readonlyRoot=$(grep "/dev/root" /proc/mounts | grep -c "\sro[\s,]")
[[ $readonlyRoot -ne 0 ]] && mount -o remount,rw /

backtitle="Homegear Nightly Installer"
installedPackages=$(dpkg-query -W -f '${db:Status-Abbrev}|${binary:Package}\n' '*' 2>/dev/null | grep '^ii' | awk -F '|' '{print $2}' | cut -d ':' -f 1)
neededDependencies="lsb-release dialog apt-utils curl gnupg apt-transport-https"
dependencies=()

for package in $neededDependencies; do
	grep -q -x -e "$package" <<< "$installedPackages"
	[[ $? -ne 0 ]] && dependencies+=("$package")
done

if [[ ${#dependencies[@]} -gt 0 ]]; then
	echo "Installing dependencies..."
	apt-get update
	[[ $? -ne 0 ]] && exit 1
	apt-get -y --no-install-recommends -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" install "${dependencies[@]}"
	[[ $? -ne 0 ]] && exit 1
fi

distribution=$(lsb_release -i -s | tr '[:upper:]' '[:lower:]')
codename=$(lsb_release -c -s)
arch=$(dpkg --print-architecture)

supportedArchitectures=$'amd64\narmhf\narm64'
if ! grep -q -x -e "$arch" <<< "$supportedArchitectures"; then
	echo "Architecture $arch is not supported."
	exit 1
fi

supportedDistributions=$'debian\nraspbian\nubuntu'
supportedCodenames=$'wheezy\njessie\nstretch\nbuster\ntrusty\nxenial\nbionic\nfocal'
if ! grep -q -x -e "$distribution" <<< "$supportedDistributions" || ! grep -q -x -e "$codename" <<< "$supportedCodenames"; then
	TTY_X=$(($(stty size | awk '{print $2}')-6))
	TTY_Y=$(($(stty size | awk '{print $1}')-6))
	distributionOptions=("1" "Debian" ON)
	distributionOptions+=("2" "Ubuntu" OFF)
	distributionOptions+=("3" "Raspbian" OFF)
	system=$(dialog --stdout --backtitle "$backtitle" --radiolist "Choose Distribution" $TTY_Y $TTY_X $(($TTY_Y - 8)) "${distributionOptions[@]}")
	[ $? -ne 0 ] && exit 1
	if [ $system -eq 1 ]; then
		distributionOptions=("1" "Debian 10 (Buster)" ON)
		distributionOptions+=("2" "Debian 9 (Stretch)" OFF)
		system=$(dialog --stdout --backtitle "$backtitle" --radiolist "Choose Distribution" $TTY_Y $TTY_X $(($TTY_Y - 8)) "${distributionOptions[@]}")
		[ $? -ne 0 ] && exit 1
		if [ $system -eq 1 ]; then
			distribution="debian"
			codename="buster"
			system="debian_buster"
		elif [ $system -eq 2 ]; then
			distribution="debian"
			codename="stretch"
			system="debian_stretch"
		fi
	elif [ $system -eq 2 ]; then
		distributionOptions=("1" "Ubuntu 20.04 (Focal Fossa)" ON)
		distributionOptions+=("2" "Ubuntu 18.04 (Bionic Beaver)" OFF)
		system=$(dialog --stdout --backtitle "$backtitle" --radiolist "Choose Distribution" $TTY_Y $TTY_X $(($TTY_Y - 8)) "${distributionOptions[@]}")
		[ $? -ne 0 ] && exit 1
		if [ $system -eq 1 ]; then
			distribution="ubuntu"
			codename="focal"
			system="ubuntu_focal"
		elif [ $system -eq 2 ]; then
			distribution="ubuntu"
			codename="bionic"
			system="ubuntu_bionic"
		fi
	elif [ $system -eq 3 ]; then
		distributionOptions=("1" "Raspbian 10 (Buster)" ON)
		distributionOptions+=("2" "Raspbian 9 (Stretch)" OFF)
		system=$(dialog --stdout --backtitle "$backtitle" --radiolist "Choose Distribution" $TTY_Y $TTY_X $(($TTY_Y - 8)) "${distributionOptions[@]}")
		[ $? -ne 0 ] && exit 1
		if [ $system -eq 1 ]; then
			distribution="raspbian"
			codename="buster"
			system="raspbian_buster"
		elif [ $system -eq 2 ]; then
			distribution="raspbian"
			codename="stretch"
			system="raspbian_stretch"
		fi
	fi
else
	system=${distribution}_${codename}
fi

buildVersion=$(curl -s "https://downloads.homegear.eu/getNightlyBuildInfo.php?f=libhomegear-base_${builddate}_${system}_${arch}.deb&t=version")
buildTime=$(curl -s "https://downloads.homegear.eu/getNightlyBuildInfo.php?f=libhomegear-base_${builddate}_${system}_${arch}.deb&t=date")
backtitle="$backtitle - Version: ${buildVersion} (build time: ${buildTime})"

function moduleInstalled()
{
	installed=$(dpkg-query -W -f='${Status}\n' $1 2>/dev/null | grep -c installed);
	if [ $installed -eq 1 ]; then
		echo -n ON
	else
		echo -n OFF
	fi
}

function moduleInstalled2()
{
	installed=$(dpkg-query -W -f='${Status}\n' $1 2>/dev/null | grep -c installed);
	if [ $installed -eq 1 ]; then
		return 0
	else
		return 1
	fi
}

TTY_X=$(($(stty size | awk '{print $2}')-6))
TTY_Y=$(($(stty size | awk '{print $1}')-6))
moduleOptions=("01" "HomeMatic BidCoS" $(moduleInstalled homegear-homematicbidcos))
moduleOptions+=("02" "HomeMatic Wired" $(moduleInstalled homegear-homematicwired))
moduleOptions+=("03" "Insteon" $(moduleInstalled homegear-insteon))
moduleOptions+=("04" "MAX!" $(moduleInstalled homegear-max))
moduleOptions+=("05" "Philips Hue" $(moduleInstalled homegear-philipshue))
moduleOptions+=("06" "Sonos" $(moduleInstalled homegear-sonos))
moduleOptions+=("09" "Kodi" $(moduleInstalled homegear-kodi))
moduleOptions+=("10" "IP Cam" $(moduleInstalled homegear-ipcam))
moduleOptions+=("11" "Beckhoff BK90x0" $(moduleInstalled homegear-beckhoff))
moduleOptions+=("14" "KNX" $(moduleInstalled homegear-knx))
moduleOptions+=("15" "EnOcean" $(moduleInstalled homegear-enocean))
moduleOptions+=("16" "Intertechno" $(moduleInstalled homegear-intertechno))
moduleOptions+=("17" "Z-Wave" $(moduleInstalled homegear-zwave))
moduleOptions+=("19" "Renkforce (Conrad RS2W)" $(moduleInstalled homegear-rs2w))
moduleOptions+=("20" "Conrad RSL" $(moduleInstalled homegear-rsl))
moduleOptions+=("22" "Nanoleaf" $(moduleInstalled homegear-nanoleaf))
moduleOptions+=("23" "wM-Bus" $(moduleInstalled homegear-mbus))
moduleOptions+=("24" "HomeMatic CCU" $(moduleInstalled homegear-ccu))
moduleOptions+=("26" "Zigbee" $(moduleInstalled homegear-zigbee))
moduleOptions+=("27" "Velux KLF200" $(moduleInstalled homegear-velux-klf200))
moduleOptions+=("28" "ABI MC 1500" $(moduleInstalled homegear-abi))
moduleOptions+=("95" "UI" $(moduleInstalled homegear-ui))
moduleOptions+=("96" "WebSSH Client" $(moduleInstalled homegear-webssh))
moduleOptions+=("97" "Management Client" $(moduleInstalled homegear-management))
moduleOptions+=("98" "Admin UI" $(moduleInstalled homegear-adminui))
moduleOptions+=("99" "InfluxDB Client" $(moduleInstalled homegear-influxdb))
extraModules=()
while true; do
	modules=$(dialog --stdout --backtitle "$backtitle" --extra-button --extra-label "Extra modules" --checklist "Choose Homegear modules" $TTY_Y $TTY_X $(($TTY_Y - 8)) "${moduleOptions[@]}")
	exitcode=$?
	[[ $exitcode -eq 1 ]] && exit 1
	[[ $exitcode -eq 255 ]] && exit 1
	moduleInstalled2 homegear-easycam && extraModules+=(homegear-easycam)
	moduleInstalled2 homegear-easyled && extraModules+=(homegear-easyled)
	moduleInstalled2 homegear-easyled2 && extraModules+=(homegear-easyled2)
	moduleInstalled2 binrpc && extraModules+=(binrpc)
	moduleInstalled2 homegear-dc-connector && extraModules+=(homegear-dc-connector)
	moduleInstalled2 homegear-cloudconnect && extraModules+=(homegear-cloudconnect)
	moduleInstalled2 ibs-ssh && extraModules+=(ibs-ssh)
	if [[ $exitcode -eq 3 ]]; then
		TTY_X=$(($(stty size | awk '{print $2}')-6))
		TTY_Y=$(($(stty size | awk '{print $1}')-6))
		extraModuleOptions=("07" "EASYCam" $(moduleInstalled homegear-easycam))
		extraModuleOptions+=("08" "EASYLed" $(moduleInstalled homegear-easyled))
		extraModuleOptions+=("18" "EASYLed 2" $(moduleInstalled homegear-easyled2))
		extraModuleOptions+=("93" "Binary RPC test tool" $(moduleInstalled binrpc))
		extraModuleOptions+=("94" "Homegear Daisy Chain Connector" $(moduleInstalled homegear-dc-connector))
		extraModuleOptions+=("91" "Homegear Cloudconnect" $(moduleInstalled homegear-cloudconnect))
		extraModuleOptions+=("92" "ib symphony SSH" $(moduleInstalled ibs-ssh))
		extraModules2=$(dialog --stdout --backtitle "$backtitle" --checklist "Choose Homegear modules" $TTY_Y $TTY_X $(($TTY_Y - 8)) "${extraModuleOptions[@]}")
		exitcode2=$?
		[[ $exitcode2 -eq 1 ]] && continue
		[[ $exitcode2 -eq 255 ]] && continue
	fi
	break
done
if [[ -n $extraModules2 ]]; then
	modules+=" $extraModules2"
else
	modules+=" $extraModules"
fi

packages=()
[[ "$modules" == *"01"* ]] && packages+="homegear-homematicbidcos "
[[ "$modules" == *"02"* ]] && packages+="homegear-homematicwired "
[[ "$modules" == *"03"* ]] && packages+="homegear-insteon "
[[ "$modules" == *"04"* ]] && packages+="homegear-max "
[[ "$modules" == *"05"* ]] && packages+="homegear-philipshue "
[[ "$modules" == *"06"* ]] && packages+="homegear-sonos "
[[ "$modules" == *"07"* ]] && packages+="homegear-easycam "
[[ "$modules" == *"08"* ]] && packages+="homegear-easyled "
[[ "$modules" == *"09"* ]] && packages+="homegear-kodi "
[[ "$modules" == *"10"* ]] && packages+="homegear-ipcam "
[[ "$modules" == *"11"* ]] && packages+="homegear-beckhoff "
[[ "$modules" == *"14"* ]] && packages+="homegear-knx "
[[ "$modules" == *"15"* ]] && packages+="homegear-enocean "
[[ "$modules" == *"16"* ]] && packages+="homegear-intertechno "
[[ "$modules" == *"17"* ]] && packages+="homegear-zwave "
[[ "$modules" == *"18"* ]] && packages+="homegear-easyled2 "
[[ "$modules" == *"19"* ]] && packages+="homegear-rs2w "
[[ "$modules" == *"20"* ]] && packages+="homegear-rsl "
[[ "$modules" == *"22"* ]] && packages+="homegear-nanoleaf "
[[ "$modules" == *"23"* ]] && packages+="homegear-mbus "
[[ "$modules" == *"24"* ]] && packages+="homegear-ccu "
[[ "$modules" == *"26"* ]] && packages+="homegear-zigbee "
[[ "$modules" == *"27"* ]] && packages+="homegear-velux-klf200 "
[[ "$modules" == *"28"* ]] && packages+="homegear-abi "
[[ "$modules" == *"91"* ]] && packages+="homegear-cloudconnect "
[[ "$modules" == *"92"* ]] && packages+="ibs-ssh "
[[ "$modules" == *"93"* ]] && packages+="binrpc "
[[ "$modules" == *"94"* ]] && packages+="homegear-dc-connector "
[[ "$modules" == *"95"* ]] && packages+="homegear-ui "
[[ "$modules" == *"96"* ]] && packages+="homegear-webssh "
[[ "$modules" == *"97"* ]] && packages+="homegear-management "
[[ "$modules" == *"98"* ]] && packages+="homegear-adminui "
[[ "$modules" == *"99"* ]] && packages+="homegear-influxdb "

curl https://apt.homegear.eu/Release.key | apt-key add -

echo "deb https://apt.homegear.eu/$(tr '[:lower:]' '[:upper:]' <<< ${distribution:0:1})${distribution:1}/ ${codename}/" > /etc/apt/sources.list.d/homegear.list
echo "deb https://aptnightly.homegear.eu/$(tr '[:lower:]' '[:upper:]' <<< ${distribution:0:1})${distribution:1}/ ${codename}/" >> /etc/apt/sources.list.d/homegear.list

TTY_X=$(($(stty size | awk '{print $2}')-6))
TTY_Y=$(($(stty size | awk '{print $1}')-6))
apt-get update 2>&1 | dialog --backtitle "$backtitle" --progressbox "Installing packages..." $TTY_Y $TTY_X
[[ $? -ne 0 ]] && exit 1
TTY_X=$(($(stty size | awk '{print $2}')-6))
TTY_Y=$(($(stty size | awk '{print $1}')-6))
apt-get -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" install homegear python3-homegear homegear-nodes-core homegear-nodes-extra homegear-licensing homegear-easy-licensing $packages 2>&1 | dialog --backtitle "$backtitle" --progressbox "Installing packages..." $TTY_Y $TTY_X

cd $SCRIPTDIR
rm -Rf $TEMPDIR
rm -f InstallNightly.sh

service homegear stop
if [[ "$modules" == *"96"* ]]; then
	systemctl enable homegear-webssh
fi
if [[ "$modules" == *"97"* ]]; then
	systemctl enable homegear-management
fi
if [[ "$modules" == *"99"* ]]; then
	systemctl enable homegear-influxdb
fi
if [[ "$modules" == *"94"* ]]; then
	systemctl enable homegear-dc-connector
fi
if [[ "$modules" == *"91"* ]]; then
	systemctl enable homegear-cloudconnect
fi
sync
sleep 5
[[ $readonlyRoot -ne 0 ]] && mount -o remount,ro /
service homegear start
if [[ "$modules" == *"96"* ]]; then
	service homegear-webssh start
fi
if [[ "$modules" == *"97"* ]]; then
	service homegear-management start
fi
if [[ "$modules" == *"99"* ]]; then
	service homegear-influxdb start
fi
if [[ "$modules" == *"94"* ]]; then
	service homegear-dc-connector start
fi
if [[ "$modules" == *"91"* ]]; then
	service homegear-cloudconnect start
fi
