#!/bin/bash
#  supervision de sympa
#KAZ_ROOT=$(cd "$(dirname $0)"/..; pwd)
KAZ_ROOT=/kaz
. $KAZ_ROOT/bin/.commonFunctions.sh
setKazVars

. $DOCKERS_ENV
. $KAZ_KEY_DIR/env-mattermostAdmin

DOCKER_CMD="docker exec sympaServ"
URL_AGORA=$(echo $matterHost).$(echo $domain)

docker exec ${mattermostServName} bin/mmctl --suppress-warnings auth login $httpProto://$URL_AGORA --name local-server --username $mattermost_user --password $mattermost_pass >/dev/null 2>&1

DateFrom() {
	OLDLANG=$LANG
	LANG=C
	declare -A TABDATE
	TABDATE[0,1]=Jan
	TABDATE[0,2]=Feb
	TABDATE[0,3]=Mar
	TABDATE[0,4]=Apr
	TABDATE[0,5]=May
	TABDATE[0,6]=Jun
	TABDATE[0,7]=Jul
	TABDATE[0,8]=Aug
	TABDATE[0,9]=Sep
	TABDATE[0,10]=Oct
	TABDATE[0,11]=Nov
	TABDATE[0,12]=Dec

	MOISCOURANT=$(date +%m | sed -e 's/^0//')
	MOISPRECEDENT=$(expr ${MOISCOURANT} - 1 )
	JOURCOURANT=$(date +%d)
	HEUREPRECEDENTE=$(date -d '6 hour ago' +%H)

	GAMMEDATE=$(echo ${TABDATE[0,$MOISCOURANT]} ${JOURCOURANT};echo "|";echo ${TABDATE[0,$MOISPRECEDENT]} ${JOURCOURANT})
	LANG=$OLDLANG
	if [ "$1" = "-h" ]
	then
		echo "${TABDATE[0,$MOISCOURANT]} ${JOURCOURANT} ${HEUREPRECEDENTE}"
	else
		echo ${GAMMEDATE}
	fi
}

PERIODE_RECHERCHE=$(DateFrom -h)
echo "Recherche à partir de ${PERIODE_RECHERCHE} heure(s)"

OLDIFS=$IFS
IFS=" "

FILTER_ERR=$(${DOCKER_CMD} grep -E "${PERIODE_RECHERCHE}" /var/log/mail.err | grep filter.sh | awk '{print $4}' | sort -u)
COUNT_FILTER=$(${DOCKER_CMD} grep -E "${PERIODE_RECHERCHE}" /var/log/mail.err | grep filter.sh | awk '{print $4}' | sort -u | wc -w)

if [ "$COUNT_FILTER" -gt 1 ]
then
   echo "---------------------------------------------------------- "
   echo $FILTER_ERR
   docker exec mattermostServ bin/mmctl post create kaz:Sysadmin-alertes --message "Recherche à partir de ${PERIODE_RECHERCHE} Heure(s)" >/dev/null 2>&1
   docker exec mattermostServ bin/mmctl post create kaz:Sysadmin-alertes --message "L' id message(s): $FILTER_ERR" >/dev/null 2>&1
   echo "---------------------------------------------------------- "
   echo "alerte filter sympa : $COUNT_FILTER "
   docker exec mattermostServ bin/mmctl post create kaz:Sysadmin-alertes --message "alerte filter sympa : $COUNT_FILTER" >/dev/null 2>&1
fi


QUEUE_MAIL=$(${DOCKER_CMD} mailq | grep @)
COUNT_MAILQ=$(${DOCKER_CMD} mailq | grep -v makerspace56 | grep -c "^[A-F0-9]")

if [ "$COUNT_MAILQ" -gt 50 ]; then
   echo "---------------------------------------------------------- "
   echo ${QUEUE_MAIL}
   echo "---------------------------------------------------------- "
   echo "alerte mailq sympa : ${COUNT_MAILQ}"
   docker exec  mattermostServ bin/mmctl post create kaz:Sysadmin-alertes --message "Recherche de ${PERIODE_RECHERCHE}" >/dev/null 2>&1
   docker exec  mattermostServ bin/mmctl post create kaz:Sysadmin-alertes --message "${QUEUE_MAIL}" >/dev/null 2>&1
   docker exec  mattermostServ bin/mmctl post create kaz:Sysadmin-alertes --message "alerte mailq sympa : ${COUNT_MAILQ}" >/dev/null 2>&1
fi
