#!/bin/bash
export $(egrep -v '^#' /usr/local/app/.env | xargs)

status_check=`psql $DATABASE_URL -c "select id, to_char(created at time zone 'Europe/Moscow', 'YYYY-MM-DD HH24:MI:SS') as created, status from tasks where status in ('normalized', 'charged') or status is null"`
status_check_count=`echo $status_check | grep -Po "\(\d+ row\)" | grep -Po "\d+"`

if [ $status_check_count -gt 10 ]; then
  status_check_title="@MegaDiablo @dregenor \n\n<b>There are more than 10 incompleted tasks</b>"
  curl -X POST https://api.telegram.org/bot$TELEGRAM_TOKEN/sendMessage -H 'Content-Type: application/json' -d '{"chat_id":-1001132297119,"text":"'"$status_check_title"'\n\n<pre>'"$status_check"'</pre>","parse_mode":"HTML"}'
fi

work_check=`psql $DATABASE_URL -c "select exists(select id from tasks where created > now() - '10 minutes'::interval)" -t`
work_check_result=`echo $work_check | tail -n1 | grep -Po "[tf]"`
if [ "$work_check_result" == "f" ]; then
  work_check_title="@MegaDiablo @dregenor \n\n<b>There are no tasks in last 10 minutes</b>"
  curl -X POST https://api.telegram.org/bot$TELEGRAM_TOKEN/sendMessage -H 'Content-Type: application/json' -d '{"chat_id":-1001132297119,"text":"'"$work_check_title"'","parse_mode":"HTML"}'
fi
