#!/bin/sh
# Sample script for purging old records from EMG database
# Routelog (and related) entries older than 180 days are deleted

dbhost=127.0.0.1
dbname=emg
dbuser=emguser
dbpassword=YOUR_DB_PASSWORD

routelog_expire=180

# Limit max number of entries to delete per run
delete_limit=10000

date

mysql -v -v -h$dbhost -u$dbuser -p$dbpassword $dbname <<EOF
CREATE TEMPORARY TABLE tmp_msgid AS (SELECT msgid FROM routelog WHERE starttime < DATE_SUB(NOW(), INTERVAL $routelog_expire DAY) LIMIT $delete_limit);
DELETE messagebody FROM messagebody INNER JOIN tmp_msgid ON messagebody.id = tmp_msgid.msgid;
DELETE messageoption FROM messageoption INNER JOIN tmp_msgid ON messageoption.id = tmp_msgid.msgid;
DELETE emgp_jobrecipient FROM emgp_jobrecipient INNER JOIN tmp_msgid ON emgp_jobrecipient.msgid = tmp_msgid.msgid;
DELETE routelog FROM routelog INNER JOIN tmp_msgid ON routelog.msgid = tmp_msgid.msgid;
DROP TABLE tmp_msgid;
DELETE FROM pdulog WHERE created < DATE_SUB(NOW(), INTERVAL 3 DAY) LIMIT $delete_limit;
EOF

exit 0

