#!/bin/bash

source /opt/scripts_local/shared_functions.sh
type -p gpg >/dev/null || (sudo apt install gnupg -y)

download_template() {
  local MY_TEMPLATE=$1
  local DST_PATH=$2
  HOSTNAME=$(hostname)
  echo "No downloading template $MY_TEMPLATE ..."  
  sudo rsync -avP -e "ssh -o StrictHostKeyChecking=no" dbi@ket.inxs.me:"$MY_TEMPLATE" "$DST_PATH"
}

install_package() {
  local MY_PACKAGE=$1
  local MY_PACKAGE_FULLPATH="/myshares/scripts/setup/$MY_PACKAGE"
  local DST_PATH="/tmp/$MY_PACKAGE"
  HOSTNAME=$(hostname)
  echo "Downloading package $1..."
  sudo rsync -avP -e "ssh -o StrictHostKeyChecking=no" "dbi@ket.inxs.me:$MY_PACKAGE_FULLPATH" "$DST_PATH"
  sudo chmod +x "$DST_PATH"
  source "$DST_PATH"
}


echo "Installing cronicle if required."

if ! ( sudo /opt/cronicle/bin/control.sh status | grep "Daemon running" > /dev/null ); then
  echo "Cronicle not running. Installing."
  if ( type -p tailscale >/dev/null ); then 
    echo "Tailscale installed, proceeding with install."
    TS_IP=$(tailscale ip -4)
    CRONICLE_IP=XXX.XXX.XXX.XXX
    sudo apt update
    sudo apt upgrade -y
    sudo apt dist-upgrade -y
    sudo apt-get install yarn -y
    sudo rm -rf /opt/cronicle
    # Install node
    install_package install_nodejs.sh
    curl -s https://raw.githubusercontent.com/jhuckaby/Cronicle/master/bin/install.js | sudo node
    cd /opt/cronicle
    # Install cronicle
    sudo npm install
    sudo npm audit fix --force
    sudo node bin/build.js dist
    sudo scp -o StrictHostKeyChecking=no root@ket.inxs.me:/myshares/shared/cronicle/config.json /opt/cronicle/conf/
    search_and_replace "$CRONICLE_IP" "$TS_IP" "/opt/cronicle/conf/config.json"
    sudo /opt/cronicle/bin/control.sh start
    sleep 5
    sudo /opt/cronicle/bin/control.sh status
    sudo cp /opt/cronicle/bin/cronicled.init /etc/init.d/cronicled
    sudo chmod 775 /etc/init.d/cronicled
    sudo update-rc.d cronicled defaults
  fi
  echo "Finished Installing Cronicle"
else
  echo "Cronicle already installed and running"
fi