#!/bin/bash
if [[ "$1" == 'debug'  ]]; then set -x;		_DEBUG=$1; shift; fi
if [[ "$1" == 'debug2' ]]; then set -xvT;	_DEBUG=$1; shift; fi
if [[ "$1" == 'trace'  ]]; then 		_TRACE=$1; shift; fi
####################################################################
#-------------------
REALPATH=`realpath $0`
WHERE=`dirname $REALPATH`
ME=`basename $REALPATH`
cd $WHERE
. ../../system.conf
. ../../common.conf
. ../../common.bashlib
#-------------------
. WatchMX.conf
STAMP="`date +%Y%m%d-%H.%M`"

# MX -------------------------------------------------
#$SQL -header -csv "select date(date_intro) as "Datum", 
#			count(IP) as "Introduced", 
#			count(dropped) as "Dropped"
#		from mailhogs
#		where origin like '%MX'
#		group by datum;" > Statistics-MX.csv

$SQL -header -csv "
	select date(date_event) as "Datum", 
		(SELECT COUNT(state) FROM $TABLE
			WHERE state='INTRO' and date(date_event) = date(a.date_event) 
			  and date(date_event) != current_date )	as "Introduction",
		(SELECT COUNT(state) FROM $TABLE
			WHERE state='COUNT' and date(date_event) = date(a.date_event)
			  and date(date_event) != current_date )	as "Counted",
		(SELECT COUNT(state) FROM $TABLE
			WHERE state='DROP'  and date(date_event) = date(a.date_event)
			  and date(date_event) != current_date )	as "Dropped"
	from $TABLE a 
		where date(a.date_event) != current_date
		  and origin like '%MX'
	group by "Datum"
	order by "Datum"
	;
	" > Statistics-MX.csv

# MB -------------------------------------------------
#$SQL -header -csv "select date(date_intro) as "Datum", 
#			count(IP) as "Introduced", 
#			count(dropped) as "Dropped"
#		from mailhogs
#		where origin like '%MB'
#		group by datum;" > Statistics-MB.csv

$SQL -header -csv "
	select date(date_event) as "Datum", 
		(SELECT COUNT(state) FROM $TABLE
			WHERE state='INTRO' and date(date_event) = date(a.date_event) 
			  and date(date_event) != current_date )	as "Introduction",
		(SELECT COUNT(state) FROM $TABLE
			WHERE state='COUNT' and date(date_event) = date(a.date_event)
			  and date(date_event) != current_date )	as "Counted",
		(SELECT COUNT(state) FROM $TABLE
			WHERE state='DROP'  and date(date_event) = date(a.date_event)
			  and date(date_event) != current_date )	as "Dropped"
	from $TABLE a 
		where date(a.date_event) != current_date
		  and origin like '%MB'
	group by "Datum"
	order by "Datum"
	;
	" > Statistics-MB.csv


mail -s Statistics-MX-$STAMP -a Statistics-MX.csv -a Statistics-MB.csv $REPORTMAIL <<EOF
Your statistics report for '$ME' as of '$STAMP' in CSV format.
See attachments.
.
EOF
