#! /usr/bin/env python

# Copyright (C) 2010 Ian Zimmerman <itz@buug.org>

# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the conditions spelled out in
# the file LICENSE are met.


from __future__ import with_statement

from sortmail.msg import _MY_VERSION
from sortmail.lock import unlocking
from socket import gethostname
import sys
from contextlib import closing
from bsddb import hashopen
import shelve
import time
import optparse

op = optparse.OptionParser(usage='usage: %prog [OPTIONS] DATABASE')
op.add_option('-C', '--convert', help='convert old format ID shelf FILE',
              metavar='FILE')
op.add_option('-c', '--clean', type='float',
              help='remove entries more than SECONDS old',
              metavar='SECONDS')
op.add_option('-V', '--version', action='store_true',
              help='print package version and exit')
op.disable_interspersed_args()
opts, args = op.parse_args()

if opts.version:
    sys.stdout.write('{0}\n'.format(_MY_VERSION))
    sys.exit(0)

if len(args) != 1:
    op.print_help()
    sys.exit(2)

db_file = args[0]

if opts.convert:
    with closing(hashopen(opts.convert, 'r')) as input_db:
        with closing(shelve.open(db_file, 'c')) as output_db:
            for key, val in input_db.iteritems():
                if key == 'CLEANTIME' or key == 'FORMAT' or key == 'VERSION':
                    continue
                record = {'time': float(val), 'version': _MY_VERSION, 'host': gethostname()}
                output_db[key] = record

if opts.clean:
    now = time.time()
    with unlocking(db_file):
        with closing(shelve.open(db_file, 'c')) as db:
            keys_to_del = [k for k in db if db[k]['time'] + opts.clean < now]
            for k in keys_to_del:
                del db[k]
