#!/bin/sh

REPORT_CONFIG="/etc/clearos/proxy_report.conf"
DBINFO="/var/clearos/system_database/reports"
MYSQL="/usr/clearos/sandbox/usr/bin/mysql"

# Check database status
#----------------------

[ -e /var/lib/system-mysql/mysql.sock ] || exit 0

# Grab the number of records to keep
#-----------------------------------

RECORDS=`grep ^records $REPORT_CONFIG 2>/dev/null | sed 's/.*=//'`
if [ -z "$RECORDS" ]; then
	RECORDS=2000000
fi

# Grab database password
#-----------------------

DBPASS=`grep ^password $DBINFO 2>/dev/null | sed "s/^password[[:space:]]*=[[:space:]]*//"`

if [ -z "$DBPASS" ]; then
    echo "Unable to authenticate with database"
    exit 1
fi

# Recreate table (if autoindex missing)
#--------------------------------------

# This was taken from reports_database/packaging/purge-report-tables.  Will merge later.
BASENAME="proxy"

BAD_INDEX_EXISTS=`$MYSQL -ureports -p"$DBPASS" -e "SELECT * FROM ${BASENAME} WHERE id = 0 LIMIT 1;" reports 2>/dev/null`

if ( [ -n "$BAD_INDEX_EXISTS" ] ); then
    echo "Re-creating tables for ${BASENAME}"
    logger -p local6.notice -t installer "app-reports-database-core - re-creating tables for $BASENAME"
    $MYSQL -ureports -p"$DBPASS" reports < /usr/clearos/apps/${BASENAME}_report/deploy/db_tables.sql
fi

# Purge database
#---------------

$MYSQL -ureports -p"$DBPASS" -e "\
DROP TABLE IF EXISTS ${BASENAME}_prune; \
CREATE TABLE ${BASENAME}_prune LIKE ${BASENAME}; INSERT INTO ${BASENAME}_prune SELECT * FROM ${BASENAME} ORDER BY timestamp DESC LIMIT ${RECORDS}; \
RENAME TABLE ${BASENAME} TO ${BASENAME}_old, ${BASENAME}_prune TO ${BASENAME};  \
DROP TABLE ${BASENAME}_old; \
" reports
