#!/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 /

free_log_space=$(df -P -B 1 /var/log | tail -1 | awk '{print $4}')
if [[ $free_log_space -lt 10000000 ]]; then
  /usr/sbin/logrotate -s /data/logrotate-status -f /etc/logrotate.conf
  # Restart rsyslog because of bug in logrotate config of older images
  systemctl restart rsyslog
  /usr/sbin/logrotate -s /data/logrotate-status -f /etc/logrotate.conf
  free_log_space=$(df -P -B 1 /var/log | tail -1 | awk '{print $4}')
  if [[ $free_log_space -lt 10000000 ]]; then
    sync
    sleep 5
    [[ $readonlyRoot -ne 0 ]] && mount -o remount,ro /
    exit 1
  fi
fi

backtitle="Homegear 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

TTY_X=$(($(stty size | awk '{print $2}')-6))
TTY_Y=$(($(stty size | awk '{print $1}')-6))
branchOptions=("1" "Stable" ON)
branchOptions+=("2" "Testing" OFF)
branchOptions+=("3" "Nightly" OFF)
branch=$(dialog --stdout --backtitle "$backtitle" --radiolist "Choose Branch" $TTY_Y $TTY_X $(($TTY_Y - 8)) "${branchOptions[@]}")
if [[ $branch == 1 ]]; then
	branch="stable"
elif [[ $branch == 2 ]]; then
	branch="testing"
elif [[ $branch == 3 ]]; then
	branch="nightly"
else
	echo "Unknown branch"
	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\nbullseye\nbookworm\ntrusty\nxenial\nbionic\nfocal\njammy\nnoble'
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" "Raspberry Pi OS" 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 12 (Bookworm)" ON)
		distributionOptions=("2" "Debian 11 (Bullseye)" ON)
		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="bookworm"
			system="debian_bookworm"
		elif [ $system -eq 2 ]; then
			distribution="debian"
			codename="bullseye"
			system="debian_bullseye"
		fi
	elif [ $system -eq 2 ]; then
		distributionOptions=("1" "Ubuntu 24.04 (Noble Numbat)" ON)
		distributionOptions+=("2" "Ubuntu 22.04 (Jammy Jellyfish)" 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="noble"
			system="ubuntu_noble"
		elif [ $system -eq 2 ]; then
			distribution="ubuntu"
			codename="jammy"
			system="ubuntu_jammy"
		fi
	elif [ $system -eq 3 ]; then
		distributionOptions=("1" "Raspberry Pi OS 12 (Bookworm)" ON)
		distributionOptions+=("2" "Raspberry Pi OS 11 (Bullseye)" 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="bookworm"
			system="raspberry_pi_os_bookworm"
		elif [ $system -eq 2 ]; then
			distribution="raspbian"
			codename="buster"
			system="raspberry_pi_os_bullseye"
		fi
	fi
else
	system=${distribution}_${codename}
fi

if [[ $distribution == "raspbian" ]]; then
	distribution="raspberry_pi_os"
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+=("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+=("22" "Nanoleaf" $(moduleInstalled homegear-nanoleaf))
moduleOptions+=("23" "wM-Bus" $(moduleInstalled homegear-mbus))
moduleOptions+=("24" "HomeMatic CCU" $(moduleInstalled homegear-ccu))
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))
moduleOptions+=("93" "Binary RPC test tool" $(moduleInstalled binrpc))
moduleOptions+=("91" "Homegear Cloudconnect" $(moduleInstalled homegear-cloudconnect))
extraModules=()
modules=$(dialog --stdout --backtitle "$backtitle" --checklist "Choose Homegear modules" $TTY_Y $TTY_X $(($TTY_Y - 8)) "${moduleOptions[@]}")
exitcode=$?
[[ $exitcode -eq 1 ]] && exit 1
[[ $exitcode -eq 255 ]] && exit 1

function downloadModule {
	if [[ "$modules" == *"${1}"* ]]; then
		TTY_X=$(($(stty size | awk '{print $2}')-6))
		TTY_Y=$(($(stty size | awk '{print $1}')-6))
		wget https://downloads.homegear.eu/nightlies/${2} 2>&1 | dialog --backtitle "$backtitle" --progressbox "Downloading ${2}..." $TTY_Y $TTY_X
		[[ ${PIPESTATUS[0]} -ne 0 ]] && exit 1
	fi
}

function installModule {
	if [[ "$modules" == *"${1}"* ]]; then
		TTY_X=$(($(stty size | awk '{print $2}')-6))
		TTY_Y=$(($(stty size | awk '{print $1}')-6))
		dpkg --force-confdef --force-confold -i ${2} 2>&1 | dialog --backtitle "$backtitle" --progressbox "Installing ${2}..." $TTY_Y $TTY_X
		if [[ ${PIPESTATUS[0]} -ne 0 ]]; then
			apt-get -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" -y -f install | dialog --backtitle "$backtitle" --progressbox "Installing dependencies..." $TTY_Y $TTY_X
			[[ ${PIPESTATUS[0]} -ne 0 ]] && exit 1
			dpkg --force-confdef --force-confold -i ${2} 2>&1 | dialog --backtitle "$backtitle" --progressbox "Installing ${2}..." $TTY_Y $TTY_X
			[[ ${PIPESTATUS[0]} -ne 0 ]] && exit 1
		fi
	fi
}

function installModuleOverwriteConfig {
	if [[ "$modules" == *"${1}"* ]]; then
		TTY_X=$(($(stty size | awk '{print $2}')-6))
		TTY_Y=$(($(stty size | awk '{print $1}')-6))
		dpkg --force-confdef --force-confnew -i ${2} 2>&1 | dialog --backtitle "$backtitle" --progressbox "Installing ${2}..." $TTY_Y $TTY_X
		if [[ ${PIPESTATUS[0]} -ne 0 ]]; then
			apt-get -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" -y -f install | dialog --backtitle "$backtitle" --progressbox "Installing dependencies..." $TTY_Y $TTY_X
			[[ ${PIPESTATUS[0]} -ne 0 ]] && exit 1
			dpkg --force-confdef --force-confnew -i ${2} 2>&1 | dialog --backtitle "$backtitle" --progressbox "Installing ${2}..." $TTY_Y $TTY_X
			[[ ${PIPESTATUS[0]} -ne 0 ]] && exit 1
		fi
	fi
}

if [[ -n $2 ]]; then
	echo "Sleeping $2 seconds"
	sleep $2
	[[ $readonlyRoot -ne 0 ]] && mount -o remount,rw /
fi

curl -fsSL https://apt.homegear.eu/Release.key | gpg --dearmor -o /usr/share/keyrings/homegear-archive-keyring.gpg

echo "deb [signed-by=/usr/share/keyrings/homegear-archive-keyring.gpg] https://apt.homegear.eu/${distribution}/${codename}/homegear/${branch}/ ${codename} main" > /etc/apt/sources.list.d/homegear.list

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" == *"09"* ]] && packages+="homegear-kodi "
[[ "$modules" == *"11"* ]] && packages+="homegear-beckhoff "
[[ "$modules" == *"14"* ]] && packages+="homegear-knx "
[[ "$modules" == *"15"* ]] && packages+="homegear-enocean "
[[ "$modules" == *"16"* ]] && packages+="homegear-intertechno "
[[ "$modules" == *"22"* ]] && packages+="homegear-nanoleaf "
[[ "$modules" == *"23"* ]] && packages+="homegear-mbus "
[[ "$modules" == *"24"* ]] && packages+="homegear-ccu "
[[ "$modules" == *"28"* ]] && packages+="homegear-abi "
[[ "$modules" == *"91"* ]] && packages+="homegear-cloudconnect "
[[ "$modules" == *"93"* ]] && packages+="binrpc "
[[ "$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 "

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 libhomegear-node libhomegear-ipc libhomegear-base nodejs-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 -f HomegearInstaller.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" == *"91"* ]]; then
	systemctl enable homegear-cloudconnect
fi
sync
dialog --no-cancel --stdout --title "Setup finished" --no-tags --pause "Rebooting in 10 seconds..." 10 50 10
reboot
