#! /opt/mailman/mm/venv/bin/python
import os
import sys
import datetime

from mailbox import mbox

sys.path.insert(0, '/opt/mailman/mm')
# The above line is required. The next line doesn't hurt, but it doesn't work
# because the PYTHONPATH environment setting is processed by Python's setup
# and must be in the environment when Python starts to be effective.
os.environ['PYTHONPATH'] = '/opt/mailman/mm'
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

import django
django.setup()
from django.db import DatabaseError
from hyperkitty.models.email import Email

CUTOFF = datetime.datetime.today() - datetime.timedelta(days=365*5)
mbox = mbox('/opt/mailman/pruned.mbox')

for email in Email.objects.filter(date__lt=CUTOFF):
    # To do just one list.
    # if email.mailinglist.list_id != 'list.example.com':
    #     continue
    try:
        mbox.add(email.as_bytes())
    except ValueError as e:
        print("Could not get email %(msg_id_hash)s as a message:"
              "%(error)s"
             % {"msg_id_hash": email.message_id_hash, "error": e})
        continue
    try:
        email.delete()
    except DatabaseError as e:
        print("Could not delete message %(msg_id_hash)s: "
              "%(error)s"
             % {"msg_id_hash": email.message_id_hash, "error": e})
    else:
        print("Deleted message %(msg_id_hash)s"
             % {"msg_id_hash": email.message_id_hash})
