#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
from time import time
from twisted.internet import reactor, defer
from txjsonrpc.web.jsonrpc import Proxy
from hyphe_backend.lib import config_hci

config = config_hci.load_config()
if not config:
    exit()

daysback = 7
if len(sys.argv) > 1:
    try:
        daysback = int(sys.argv[1])
    except:
        print >> sys.stderr, "ERROR: argument must be an integer (number of days back)"
        exit(1)
dayms = 1000 * 60 * 60 * 24
delay = dayms * daysback

proxy = Proxy('http://127.0.0.1:%d' % config['twisted.port'])

@defer.inlineCallbacks
def handleList(res):
    if res['code'] == 'fail':
        defer.returnValue(printError(res['message']))
    for cid, corpus in res['result'].items():
        since = time() * 1000 - corpus['last_activity']
        if since > delay:
            print "SHOULD REMOVE:", cid, corpus['last_activity'], int((since - delay) / dayms), "days old"
            res = yield proxy.callRemote('start_corpus', cid, 'hyphe déchire!' if corpus['password'] else '')
            if res['code'] == 'fail':
                logging.error("WARNING: could not start old corpus %s: %s" % (cid, res['message']))
                continue
            res = yield proxy.callRemote('ping', cid, 30)
            if res['code'] == 'fail':
                logging.error("WARNING: could not ping old corpus %s: %s" % (cid, res['message']))
                continue
            res = yield proxy.callRemote('destroy_corpus', cid)
            if res['code'] == 'fail':
                logging.error("WARNING: could not destroy old corpus %s: %s" % (cid, res['message']))


def printError(error):
    print >> sys.stderr, "ERROR: Cannot get list of corpora", error

def shutdown(data):
    reactor.stop()

d = proxy.callRemote('list_corpus')
d.addCallback(handleList).addErrback(printError)
d.addCallback(shutdown)
reactor.run()

add script to cleanup old corpora