#!/bin/sh

#
# Daily and hourly maintenance job
# - database backup
# - copy database to sandbox database
# - garbage collect database
# - spool expiration
#
# This script is meant to be run by cron, with entries such as:
#	0 8-18 * * * netmagis /usr/local/sbin/netmagis-dbmaint hourly
#	0 23   * * * netmagis /usr/local/sbin/netmagis-dbmaint daily
#
# History
#   2002/06/04 : pda : design script to copy to development database
#   2002/06/19 : pda : design backup script
#   2002/07/25 : pda : merge in only one script
#   2011/03/18 : pda : i18n
#   2012/06/19 : pda : create copy database and simplify copying
#

usage ()
{
    echo "usage: $0 hourly|daily" >&2
    exit 1
}

##############################################################################
# Configuration file read
##############################################################################

init_env ()
{
    varlist="dnsdbhost dnsdbport dnsdbname dnsdbuser dnsdbpassword"
    eval `/usr/local/bin/netmagis-config -c $varlist`

    if [ $? != 0 ]
    then
	usage
	exit 1
    fi

    PGHOST="$dnsdbhost"
    PGPORT="$dnsdbport"
    PGDATABASE="$dnsdbname"
    PGUSER="$dnsdbuser"
    PGPASSWORD="$dnsdbpassword"
    export PGHOST PGPORT PGDATABASE PGUSER PGPASSWORD

    # these variables are searched in a second pass, since they can be
    # empty (the first pass used the "-c" flag)
    varlist="dumpdir dbcopy"
    eval `/usr/local/bin/netmagis-config $varlist`

}

backup ()
{
    if [ "$dumpdir" != "" ]
    then
	pg_dump --file=$dumpdir/dump.$NOW \
		--schema=global --schema=dns --schema=topo --schema=pgauth \
		$PGDATABASE
    fi
}

copy ()
{
    if [ "$dumpdir" != "" -a "$dbcopy" != "" ]
    then
	# drop copy if it already exists
	if psql -lAt | grep -q "^$dbcopy|"
	then dropdb "$dbcopy"
	fi

	# create copy from the original database
	createdb -E unicode --template="$PGDATABASE" "$dbcopy"
    fi
}

vacuum ()
{
    vacuumdb --quiet --full $PGDATABASE 2>&1 \
	| grep -v "WARNING:.* only superuser can vacuum it"
    return 0
}

get_config ()
{
    psql -Aqtc "SELECT value FROM global.config WHERE key = '\$1'" $PGDATABASE
}

clean_spools ()
{
    ifchangeexpire=`get_config ifchangeexpire`
    if expr "$ifchangeexpire" : "[0-9][0-9]*$" > /dev/null
    then
	psql -d $PGDATABASE -q -c \
	    "DELETE FROM topo.ifchanges
		WHERE processed = 1 AND NOW()-reqdate > '\$ifchangexpire days'"
    fi

    modeqexpire=`get_config modeqexpire`
    if expr "$modeqexpire" : "[0-9][0-9]*$" > /dev/null
    then
	psql -d $PGDATABASE -q -c \
	    "DELETE FROM topo.modeq
		WHERE processed = 1 AND NOW()-date > '\$modeqexpire days'"
    fi
}

init_env
NOW=`date +%a-%H`			# day of week & hour

case "$1" in
    daily)
	if backup && copy && clean_spools && vacuum
	then exitcode=0
	else exitcode=1
	fi
	;;
    hourly)
	if backup
	then exitcode=0
	else exitcode=1
	fi
	;;
    *)
	usage
	;;
esac

if [ $exitcode = 1 ]
then echo "Error during daily $PGDATABASE database maintenance" >&2
fi

exit $exitcode
