#!/bin/sh
set -u
if [ "${1:-}" = "-x" ] ; then set -xv; shift; fi
#mail_address=moibenko@fnal.gov
mail_address=`enstore conf --show crons email`
timeout='--timeout 10 --retries 3'
#Obtain the Enstore DB port number.
EDB_PORT=`enstore conf $timeout --show database dbport`
if [ -z "$EDB_PORT" ]; then
    echo "dbport not found in configuration."
    exit 1
fi

#Obtain the Enstore DB name.
EDB_NAME=`enstore conf $timeout --show database dbname`
if [ -z "$EDB_NAME" ]; then
    echo "dbname not found in configuration."
    exit 1
fi

#Obtain the Enstore DB host.
EDB_HOST=`enstore conf $timeout --show database dbhost`
if [ -z "$EDB_HOST" ]; then
    echo "dbhost not found in configuration."
    exit 1
fi

#Obtain the Enstore DB user/role.
EDB_USER=`enstore conf $timeout --show database dbuser_reader`
if [ -z "$EDB_USER" ]; then
    echo "dbuser not found in configuration."
    exit 1
fi

# Check for the presence of the empty packages during last 24 hours
# and report if there are such.

psql -p $EDB_PORT -h $EDB_HOST -U $EDB_USER $EDB_NAME -t -c "select f.package_id,v.file_family from file f, volume v where f.volume=v.id and v.file_family not like '%_copy_%' and archive_mod_time > current_timestamp - interval '1 day' and f.package_id in (select package_id from file where package_files_count!=0 group by package_id having count(*)=1)" > /tmp/empty_packages

if [ `wc -l < /tmp/empty_packages` -gt 1 ]; # query returns additional empty line
then
   mail -s "Empty SFA packages found" $mail_address < /tmp/empty_packages
fi
exit 0
