#!/bin/bash

if [[ ! -f "/usr/bin/unzip" ]]
then
  echo "Installing unzip... This takes a few moments..."
  apt-get update > /dev/null 2>&1
  apt-get install -y unzip > /dev/null 2>&1
fi

if [[ ! -d "/opt/daemon/manual" ]]
then
  echo "Creating /opt/daemon/manual directory"
  mkdir -p /opt/daemon/manual
fi 

cd /opt/daemon/manual
echo "Downloading Daemon Archive"
wget "https://daemon.nitrado.net/cloud_server/daemon-latest.zip" -O /opt/daemon/manual/daemon.zip > /dev/null 2>&1

echo "Unpacking Daemon Archive"
unzip -o daemon.zip > /dev/null 2>&1
rm daemon.zip

chmod +x /opt/daemon/manual/nitrapi

echo "Changing latest symlink to manual installation"
cd /opt/daemon
rm -f latest
ln -s manual/ latest

echo "Updating systemd Service"
echo '[Unit]
Description=Nitrapi Daemon
After=network.target
ConditionDirectoryNotEmpty=/opt/daemon/latest

[Service]
Type=notify
NotifyAccess=all
ExecStart=/opt/daemon/latest/nitrapi foreground
Restart=always
RestartSec=10s
WatchdogSec=10s
PrivateTmp=true

[Install]
WantedBy=multi-user.target' > /etc/systemd/system/nitrapi-daemon.service

/bin/systemctl daemon-reload

echo "Enabling systemd nitrapi-daemon.service"
/bin/systemctl enable nitrapi-daemon.service

echo "Manual update finished"
echo "If you like, just restart/start it via \"systemctl restart nitrapi-daemon.service\""
