#!/bin/bash

tgapi=""
tgch=""

nextcloudpath="/var/www/html"
wwwuser="www-data"
logmax="250"
logprefix="checkupdates"

function sendtelegram {
  mode=$1
  if [[ $mode == "new" ]]; then
    echo "Nextcloud install needs updating..." > /tmp/nccheckupdatesheader.txt
  elif [[ $mode == "reminder" ]]; then
    echo "Reminder: Nextcloud install needs updating..." > /tmp/nccheckupdatesheader.txt
  else
    echo "Error with statement 'sendtelegram'."
    updatelog error
    exit 1
  fi
  echo "Server: $(hostname)" >> /tmp/nccheckupdatesheader.txt
  echo "Path: $nextcloudpath" >> /tmp/nccheckupdatesheader.txt
  echo "Date: $(date)" >> /tmp/nccheckupdatesheader.txt
  echo "" >> /tmp/nccheckupdatesheader.txt
  string=$(cat /tmp/nccheckupdatesheader.txt /tmp/nccheckupdates.txt)
  wget -qO- "https://api.telegram.org/bot$tgapi/sendMessage?chat_id=$tgch&text=$string" &> /dev/null
  errorcode=$?
  echo $datestamp > /tmp/nccheckupdatessent.txt
  updatelog $mode $errorcode
}

function updatelog {
  if [[ $1 == "new" ]]; then
    logdata="First Telegram Sent"
  elif [[ $1 == "reminder" ]]; then
    logdata="Reminder Telegram Sent"
  else
    logdata="Error with statement 'sendtelegram'"
  fi
  if [[ ! -z $2 ]]; then
    if [[ $2 == "0" ]]; then
      logerror="Successful!"
    else
      logerror="Sending Failed: Exit Code $2"
    fi
  fi
  echo "$(date +%y%m%d).$(date +%H%M) - $logprefix - $logdata - $logerror" >> /var/log/nextcloud-telegram-notify.log
  logsize=$(cat /var/log/nextcloud-telegram-notify.log | wc -l)
  if [[ $logsize -gt $logmax ]]; then
    mv /var/log/nextcloud-telegram-notify.log /tmp/nextcloud-telegram-notify.log
    tail -n $logmax /tmp/nextcloud-telegram-notify.log > /var/log/nextcloud-telegram-notify.log
    rm /tmp/nextcloud-telegram-notify.log
  fi
}

datestamp="$(date +%y%m%d)"

sudo -u $wwwuser php "$nextcloudpath/occ" update:check > /tmp/nccheckupdates.txt

string=$(cat /tmp/nccheckupdates.txt)

if [[ ${string:0:21} == "Everything up to date" ]]; then
  echo "All Good!"
  if [[ -f /tmp/nccheckupdatessent.txt ]]; then
    rm /tmp/nccheckupdatessent.txt
  fi
else
  if [[ ! -f /tmp/nccheckupdatessent.txt ]]; then
    echo "Update Required: Sending First Telegram..."
    sendtelegram new
  elif [[ -f /tmp/nccheckupdatessent.txt ]]; then
    laststamp=$(head -1 /tmp/nccheckupdatessent.txt)
    if [[ ${laststamp:0:6} == $datestamp ]]; then
      echo "Update Required: All ready sent Telegram today."
    else
      echo "Update Required: Sending Reminder Telegram..."
      sendtelegram reminder
    fi
  fi
fi
