#!/bin/sh
# snf_preflight script is used to check snf.db integrity and size
# before report-snf ps is started
#
RSYSLOG_ID="report-delivery"
RSYSLOG_FACILITY="local0"
SNF_DB_PATH="/data/ctm/snf.db"
TEST_MAX_DB_SIZE_FILE="/data/ctm/SNF_MAX_DBSIZE"
# max db size is set 500K larger than actual max size to allow for some margin
MAX_DB_SIZE=20500000


dbg_logger()
{
    logger -p ${RSYSLOG_FACILITY}.$1 -t ${RSYSLOG_ID} snf_preflight: $2
}

reduce_db()
{
    dbg_logger "notice" "reducing snf db size"
    max_db_size=$1
    # try pragma vacuum first
    rc=$(/usr/bin/sqlite3 ${SNF_DB_PATH} 'VACUUM;')
    db_size=$(wc -c <"$SNF_DB_PATH")
    dbg_logger "notice" "size after vacuum $db_size"
    if [ $db_size -gt $max_db_size ]; then
        # query number of rows
        rows=$(/usr/bin/sqlite3 ${SNF_DB_PATH} 'SELECT count(*) from snfdata;')
        # average row size
        avg_row_size=$(($db_size / $rows))
        dbg_logger "notice" "$rows rows in snf db, average row size $avg_row_size"
        # required reduction size
        reduct_size=$(($db_size - $max_db_size))
        # rows to delete
        num_to_delete=$(($reduct_size / $avg_row_size))
        dbg_logger "notice" "required reduction $reduct_size bytes, deleting $num_to_delete rows"
        query="DELETE FROM snfdata WHERE key IN (SELECT key FROM snfdata ORDER BY TIMESTAMP ASC LIMIT \"${num_to_delete}\");"
        rc=$(/usr/bin/sqlite3 ${SNF_DB_PATH} "$query")
        rc=$(/usr/bin/sqlite3 ${SNF_DB_PATH} 'VACUUM;')
        /bin/sync
        db_size=$(wc -c <"$SNF_DB_PATH")
        dbg_logger "notice" "reduced db size is $db_size bytes"
    fi
}

if [ -e "${SNF_DB_PATH}" ]; then
    dbg_logger "notice" "found ${SNF_DB_PATH}, running snf.db integrity check"
    rc=$(/usr/bin/sqlite3 ${SNF_DB_PATH} 'PRAGMA integrity_check')
    if [ "$rc" != "ok" ]; then
        dbg_logger "notice" "integrity check failed, deleting ${SNF_DB_PATH}"
        /bin/rm -f ${SNF_DB_PATH}
        /bin/sync
    else
        dbg_logger "notice" "integrity check ${rc}"
        # check for test max db size file
        if [ -e "${TEST_MAX_DB_SIZE_FILE}" ]; then
            max_db_size=`cat ${TEST_MAX_DB_SIZE_FILE}`
            dbg_logger "notice" "using test max db size: ${max_db_size} bytes"
        else
            max_db_size=$MAX_DB_SIZE
        fi
        # check file size
        db_size=$(wc -c <"$SNF_DB_PATH")
        dbg_logger "notice" "snf db size is ${db_size} bytes, max db size is ${max_db_size} bytes"
        if [ $db_size -gt $max_db_size ]; then
            dbg_logger "notice" "snf db size exceeds max allowable size ${max_db_size}"
            reduce_db $max_db_size
        fi
    fi
else
    dbg_logger "notice" "no snf db found, will be initialized on report-snf startup"
fi
