#!/bin/sh

sqlite=/usr/bin/sqlite3
handler_db=/var/lib/plesk/mail/handlers/handlers.db
dump_db=/var/lib/plesk/mail/handlers/protected_handlers.sql


_safe_die() 
{
	cp -f ${handler_db} ${handler_db}.bkp
	echo "Error: unable to dump handlers with protection flag."
	echo "Handlers DB will be re-inited and custom handlers will be lost."
	echo "Original DB is saved as ${handler_db}.bkp"
	exit 1
}

rm -f ${dump_db}
[ -r "${handler_db}" ] || exit 1

columns=`${sqlite} ${handler_db} 'PRAGMA table_info(handlers)' 2>/dev/null |  awk -F '|' '{print "'\''" $2 "'\''"}' | xargs -d '\n' | tr ' ' ','`
[ -n "${columns}" ] || _safe_die

echo "${columns}" | egrep "\<protected\>" >/dev/null 2>&1
if [ $? -ne 0 ]; then
	echo "Warning: there is no protected handlers flag column in handlers DB"
	exit 1
fi

handlers_content=`printf '.mode insert handlers\nSELECT * FROM handlers WHERE protected = 1;' | ${sqlite} "${handler_db}" 2>/dev/null`
if [ -z "${handlers_content}" ]; then
	echo "Info: there are no protected handlers"
	exit 1
fi

echo "${handlers_content}" | sed -e "s|\(VALUES\)|\(${columns}\)\1|g" > "${dump_db}" 2>/dev/null

[ $? -eq 0 ] && test -s "${dump_db}" || _safe_die
