#!/bin/bash

tgapi=""
tgch=""

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

function sendtelegram {
  echo "Nextcloud has new user(s)..." > /tmp/ncchecknewusersheader.txt
  echo "Server: $(hostname)" >> /tmp/ncchecknewusersheader.txt
  echo "Path: $nextcloudpath" >> /tmp/ncchecknewusersheader.txt
  echo "Date: $(date)" >> /tmp/ncchecknewusersheader.txt
  echo "" >> /tmp/ncchecknewusersheader.txt
  string=$(cat /tmp/ncchecknewusersheader.txt /tmp/ncchecknewuserslist.txt)
  wget -qO- "https://api.telegram.org/bot$tgapi/sendMessage?chat_id=$tgch&text=$string" &> /dev/null
  errorcode=$?
  echo $datestamp > /tmp/nccheckupdatessent.txt
  updatelog $errorcode
}

function updatelog {
  logdata="Telegram Sent"
  if [[ ! -z $1 ]]; then
    if [[ $1 == "0" ]]; then
      logerror="Successful!"
    else
      logerror="Sending Failed: Exit Code $1"
    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
}

sudo -u $wwwuser php "$nextcloudpath/occ" user:list > /tmp/ncchecknewusers.txt

if [[ -f /tmp/ncchecknewusers.old ]]; then
  cat /tmp/ncchecknewusers.old /tmp/ncchecknewusers.txt | sort | uniq -u > /tmp/ncchecknewusers.new
  newusers=$(cat /tmp/ncchecknewusers.new | wc -l)
  if [[ $newusers -gt 0 ]]; then
    echo "There are $newusers new users..."
    rm -f /tmp/ncchecknewuserslist.txt
    while read -r line; do
      echo "" >> /tmp/ncchecknewuserslist.txt
      array=($line)
      name=${array[1]:0:-1}
      sudo -u $wwwuser php "$nextcloudpath/occ" user:info $name >> /tmp/ncchecknewuserslist.txt
    done < /tmp/ncchecknewusers.new
    sendtelegram
  else
    echo "There are no new users..."
  fi
else
  echo "First run... saving current list of users..."
fi

mv /tmp/ncchecknewusers.txt /tmp/ncchecknewusers.old
