#!/bin/bash
export NCURSES_NO_UTF8_ACS=1

if [ "$(id -u)" != "0" ]; then
	echo "This script must be run as root!" 1>&2
	exit 1
fi
if [ ! -f /usr/bin/apt ]; then
    echo "This script needs a debian-based system!" 1>&2
    exit 1
fi

SCRIPTDIR="$( cd "$(dirname $0)" && pwd )"
CURRENTIP="$( hostname  -I | cut -f1 -d' ' )"

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

supportedArchitectures=$'amd64\narmhf\narm64'
supportedSystems=$'debian\nraspbian'
supportedCodenames=$'stretch\nbuster'
if ! grep -q -x -e "$arch" <<< "$supportedArchitectures"; then
	echo "Architecture $arch is not supported."
	exit 1
fi
if ! grep -q -x -e "$system" <<< "$supportedSystems"; then
	echo "Only Debian/Raspbian are supported."
	exit 1
fi
if ! grep -q -x -e "$codename" <<< "$supportedCodenames"; then
	echo "Only stretch/buster are supported."
	exit 1
fi
if [ $system == "debian" ] && [ $codename == "stretch" ] && [ $arch == "arm64" ]; then
    echo "Debian Stretch on arm64 is not supported."
    exit 1
fi
if [ $system == "raspbian" ]; then
  system="debian"
fi

checkManagement()
{
    local result=$(homegear -e rc 'echo call_user_func("Homegear\\Homegear::system.listMethods", "managementGetCommandStatus");' 2>&1)
    if [[ "$result" != "1" ]]; then
        sleep 1
        checkManagement
    fi
}

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

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="apt-utils gnupg1 curl dialog apt-transport-https resolvconf vim net-tools"
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

generateLocales=0
if ! grep -q -x -e "de_DE.utf8" <<< "$locales"; then
    echo 'de_DE.UTF-8 UTF-8' >> /etc/locale.gen
    generateLocales=1
fi
if ! grep -q -x -e "en_US.utf8" <<< "$locales"; then
    echo 'en_US.UTF-8 UTF-8' >> /etc/locale.gen
    generateLocales=1
fi
if [ $generateLocales == "1" ]; then
    locale-gen
fi


backtitle="smartha Installer v0.5 BETA"
TTY_X=$(($(stty size | awk '{print $2}')-6))
TTY_Y=$(($(stty size | awk '{print $1}')-6))
dialog --stdout --backtitle "$backtitle" --msgbox "Welcome to the smartha installer!\n\nThis installer will automatically install the latest version of the smartha BETA software for you." $TTY_Y $TTY_X

TTY_X=$(($(stty size | awk '{print $2}')-6))
TTY_Y=$(($(stty size | awk '{print $1}')-6))
(
    printf "Importing keys ...\n"
    curl -sL https://repos.influxdata.com/influxdb.key | apt-key add - > /dev/null 2>&1
    curl -sL https://apt.smartha.io/Release.key | apt-key add - > /dev/null 2>&1
    printf "Adding repositories ...\n"
    echo "deb https://repos.influxdata.com/debian $codename stable" > /etc/apt/sources.list.d/influxdb.list
    echo "deb https://apt.smartha.io/homegear/testing/$system/$codename $codename testing" > /etc/apt/sources.list.d/homegear.list
    echo "deb https://apt.smartha.io/testing/$system/$codename $codename testing" > /etc/apt/sources.list.d/smartha.list
    printf "Updating package list ...\n"
    apt update >/dev/null 2>&1
) | dialog --backtitle "$backtitle" --progressbox "Setting up system ..." $TTY_Y $TTY_X
exitcode=$?
[[ $exitcode -eq 1 ]] && exit 1

TTY_X=$(($(stty size | awk '{print $2}')-6))
TTY_Y=$(($(stty size | awk '{print $1}')-6))
(
    apt-get install -o Dpkg::Progress=1 -y sqlite3 openvpn influxdb mosquitto ocserv ufw homegear homegear-management homegear-webssh homegear-nodes-core homegear-nodes-extra homegear-easy-licensing \
    homegear-easyled2 homegear-easycam homegear-smartha-philipshue homegear-smartha-sonos homegear-smartha-ccu homegear-influxdb influxdb homegear-smarthaui homegear-smartha-devicedefinitions \
    homegear-smartha-nodes homegear-smartha-miscellaneous homegear-smartha-management homegear-smartha-configs 2>&1 | tee /tmp/install.log | \
    awk -W interactive '/Progress/ { print }'| sed -u 's/[^0-9]//g' 
) | dialog --backtitle "$backtitle" --gauge "Installing system, please wait.\n\nThis might take a while, depending on your hardware." $TTY_Y $TTY_X 0
exitcode=$?
[[ $exitcode -eq 1 ]] && exit 1

TTY_X=$(($(stty size | awk '{print $2}')-6))
TTY_Y=$(($(stty size | awk '{print $1}')-6))
(   
    printf "Preparing system ...\n"
    sed -i 's/^#AUTOSTART=\"none\"/AUTOSTART=\"none\"/' /etc/default/openvpn
	# add homegear-management tag for resolvconf
	printf '#{{{ homegear-management\n\n#}}} homegear-management\n' >>/etc/resolvconf/resolv.conf.d/head
    # remove possible "homegear_updated" file
	if [ -f /var/lib/homegear/homegear_updated ]; then
		rm /var/lib/homegear/homegear_updated
	fi
    printf "Stopping services ...\n"
    systemctl disable influxdb > /dev/null 2>&1
    systemctl disable mosquitto > /dev/null 2>&1
    systemctl disable ocserv > /dev/null 2>&1
    systemctl stop ocserv > /dev/null 2>&1
    mgmt="$( pidof homegear-management )"
    kill -9 $mgmt
    systemctl stop homegear-influxdb > /dev/null 2>&1
    systemctl stop homegear-webssh > /dev/null 2>&1
    systemctl stop homegear > /dev/null 2>&1
    printf "Adding user ...\n"
    adduser --disabled-password --gecos "" cmsupport > /dev/null 2>&1
    adduser --disabled-password --gecos "" user > /dev/null 2>&1
    usermod -aG homegear user > /dev/null 2>&1
    usermod -aG mosquitto homegear > /dev/null 2>&1
    printf "Configuring modules ...\n"
    for file in `find /etc/homegear/families -type f -name "*.conf"`; do
        sed -i 's/moduleEnabled = true/moduleEnabled = false/g' "$file"
    done
    sed -i 's/moduleEnabled = false/moduleEnabled = true/g' /etc/homegear/families/miscellaneous.conf 2>&1
    #sed -i 's/moduleEnabled = false/moduleEnabled = true/g' /etc/homegear/families/ccu.conf > /dev/null 2>&1
    #sed -i 's/moduleEnabled = false/moduleEnabled = true/g' /etc/homegear/families/sonos.conf > /dev/null 2>&1
    printf "Updating configuration ...\n"
    NIC="$(ip link | awk -F: '$0 !~ "lo|vir|tun|wl|wg|dummy|docker|^[^0-9]|\."{print $2;getline}' | sed -e 's/^[[:space:]]*//')"
    cat /proc/sys/kernel/random/uuid > /etc/.smartha-id
    wget -O /etc/homegear/main.conf https://smartha.io/downloads/config/homegear/main.conf > /dev/null 2>&1
    wget -O /etc/mosquitto/mosquitto.conf https://smartha.io/downloads/config/mosquitto/mosquitto.conf > /dev/null 2>&1
    if [[ $readonlyRoot -ne 0 ]]; then
        mkdir -p /data/homegear-tmp
        mkdir -p /data/homegear-data
        mkdir /data/homegear-data/db
	    mkdir /data/homegear-data/families
	    mkdir /data/homegear-data/node-blue
        mkdir -p /data/mosquitto/conf.d
        wget -O /data/mosquitto/conf.d/smartha.conf https://smartha.io/downloads/config/mosquitto/conf.d/smartha.conf > /dev/null 2>&1
        sed -i 's/^bind_interface .*/bind_interface '$NIC'/' /data/mosquitto/conf.d/smartha.conf
        touch /data/mosquitto/user.db
        chown -R mosquitto:mosquitto /data/mosquitto
        chmod g+w /data/mosquitto
        chmod g+w /data/mosquitto/user.db
        chmod g+w /data/mosquitto/conf.d
        chmod g+w /data/mosquitto/conf.d/smartha.conf
    else
        sed -i 's/^writeableDataPath = \/data\/homegear-data/writeableDataPath = \/var\/lib\/homegear/g' /etc/homegear/main.conf
        sed -i 's/^familyDataPath = .*/familyDataPath = \/var\/lib\/homegear\/families/g' /etc/homegear/main.conf
        sed -i 's/^databasePath = .*/\# databasePath = /g' /etc/homegear/main.conf
        sed -i 's/^databaseBackupPath = .*/\# databaseBackupPath = /g' /etc/homegear/main.conf
        sed -i 's/^nodeBluePath = .*/nodeBluePath = \/var\/lib\/homegear\/node-blue/g' /etc/homegear/main.conf
        sed -i 's/^nodeBlueDataPath = .*/nodeBlueDataPath = \/var\/lib\/homegear\/node-blue\/data/g' /etc/homegear/main.conf
        sed -i 's/^include_dir .*/include_dir \/etc\/mosquitto\/conf.d/' /etc/mosquitto/mosquitto.conf
        wget -O /etc/mosquitto/conf.d/smartha.conf https://smartha.io/downloads/config/mosquitto/conf.d/smartha.conf > /dev/null 2>&1
        sed -i 's/^password_file .*/password_file \/etc\/mosquitto\/user\.db/' /etc/mosquitto/conf.d/smartha.conf
        sed -i 's/^bind_interface .*/bind_interface '$NIC'/' /etc/mosquitto/conf.d/smartha.conf
        touch /etc/mosquitto/user.db
        chown -R mosquitto:mosquitto /etc/mosquitto
        chmod g+w /etc/mosquitto
        chmod g+w /etc/mosquitto/user.db
        chmod g+w /etc/mosquitto/conf.d
        chmod g+w /etc/mosquitto/conf.d/smartha.conf
    fi
    sed -i 's/^debugLevel = .*/debugLevel = 2/' /etc/homegear/main.conf
    sed -i 's/^# waitForIp4OnInterface = .*/waitForIp4OnInterface = '$NIC'/' /etc/homegear/main.conf
    sed -i 's/^waitForIp4OnInterface = .*/waitForIp4OnInterface = '$NIC'/' /etc/homegear/main.conf
    sed -i 's/^eventServerIp = .*/eventServerIp = '$NIC'/' /etc/homegear/families/ccu.conf
    sed -i 's/^host = .*/host = '$NIC'/' /etc/homegear/families/sonos.conf
    sed -i 's/APP_ENV=dev/APP_ENV=prod/g' /var/lib/homegear/ui/.env > /dev/null 2>&1
    #wget -O /etc/homegear/management.conf https://smartha.io/downloads/config/management.conf > /dev/null 2>&1
    #wget -O /etc/homegear/smartha-management.conf https://smartha.io/downloads/config/smartha-management.conf > /dev/null 2>&1
    if [ "$readonlyRoot" -eq "0" ]; then
        sed -i 's/rootIsReadOnly = true/rootIsReadOnly = false/g' /etc/homegear/management.conf > /dev/null 2>&1
        sed -i 's/rootIsReadOnly = true/rootIsReadOnly = false/g' /etc/homegear/smartha-management.conf > /dev/null 2>&1
    fi
    wget -O /etc/homegear/rpcservers.conf https://smartha.io/downloads/config/homegear/rpcservers.conf > /dev/null 2>&1
    wget -O /etc/homegear/webssh.conf https://smartha.io/downloads/config/homegear/webssh.conf > /dev/null 2>&1
    wget -O /etc/homegear/mqtt.conf https://smartha.io/downloads/config/homegear/mqtt.conf > /dev/null 2>&1
    wget -O /etc/homegear/influxdb.conf https://smartha.io/downloads/config/homegear/influxdb.conf > /dev/null 2>&1
    wget -O /etc/homegear/php.ini https://smartha.io/downloads/config/homegear/php.ini > /dev/null 2>&1
    wget -O /etc/ocserv/ocserv.conf https://smartha.io/downloads/config/ocserv/ocserv.conf > /dev/null 2>&1
    touch /etc/ocserv/user.passwd
    printf "Preparing server ...\n"
    printf "<?php\nheader('Location: /ui');\n" >/var/lib/homegear/www/index.php 2>&1
    rm -rf /var/lib/homegear/www/rpc/* > /dev/null 2>&1
    touch /var/lib/homegear/www/rpc/index.php > /dev/null 2>&1
) | dialog --backtitle "$backtitle" --progressbox "Setting up system ..." $TTY_Y $TTY_X
exitcode=$?
[[ $exitcode -eq 1 ]] && exit 1

TTY_X=$(($(stty size | awk '{print $2}')-6))
TTY_Y=$(($(stty size | awk '{print $1}')-6))
(
    printf "Starting services ...\n"
    systemctl start homegear
    sleep 2
    systemctl start homegear-management
    sleep 1
    checkManagement
    wget -O /var/lib/homegear/scripts/createCa.hgs https://smartha.io/downloads/scripts/createCa.hgs > /dev/null 2>&1
    wget -O /var/lib/homegear/scripts/createCerts.hgs https://smartha.io/downloads/scripts/createCerts.hgs > /dev/null 2>&1
    printf "Creating certificate authority (CA) ...\n"
    homegear -e rs createCa.hgs
    printf "Creating certificates ...\n"
    homegear -e rs createCerts.hgs
    rm -rf /var/lib/homegear/scripts/*.hgs > /dev/null 2>&1
    printf "Enabling services ...\n"
    systemctl enable homegear-management > /dev/null 2>&1
	systemctl enable homegear-influxdb > /dev/null 2>&1
	systemctl enable homegear-webssh > /dev/null 2>&1
	systemctl enable homegear > /dev/null 2>&1
    systemctl stop homegear  > /dev/null 2>&1
) | dialog --backtitle "$backtitle" --progressbox "Initial configuration ..." $TTY_Y $TTY_X
exitcode=$?
[[ $exitcode -eq 1 ]] && exit 1

cd $SCRIPTDIR
rm -f smarthaInstaller.sh
sync
sleep 2
[[ $readonlyRoot -ne 0 ]] && mount -o remount,ro /

TTY_X=$(($(stty size | awk '{print $2}')-6))
TTY_Y=$(($(stty size | awk '{print $1}')-6))
dialog --stdout --backtitle "$backtitle" --msgbox "Installer finished! Please reboot your system now.\n\nAfter reboot point your browser to https://$CURRENTIP in order to finish the installation." $TTY_Y $TTY_X
