import time
import sys
import os

import authentic.publisher as publisher
import authentic.sessions as sessions

def clean_vhost_sessions():
    manager = sessions.StorageSessionManager()
    one_week_ago = time.time() - 2*86400
    one_month_ago = time.time() - 30*86400
    for session_key in manager.keys():
        try:
            session = manager.get(session_key)
            if ((not hasattr(session,'_access_time')) \
                or session._access_time < one_week_ago) \
               or session._creation_time < one_month_ago:
                del manager[session.id]
        except AttributeError:
            try:
                del manager[session_key]
            except:
                pass
            continue

def clean_sessions(args):
    pub = publisher.AuthenticPublisher.create_publisher()

    if '--single_host' in args:
        clean_vhost_sessions()
    else:
        app_dir = pub.app_dir
        hostnames = os.listdir(app_dir)
        for hostname in hostnames:
            pub.app_dir = os.path.join(app_dir, hostname)
            clean_vhost_sessions()
