#!/usr/bin/python
# Copyright (C) 2011 by Marek Aaron Sapota
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

from __future__ import print_function

import os, os.path, sys, signal, argparse
from threading import Thread

from MailChariot import VERSION
import MailChariot.Configuration as Configuration
import MailChariot.PersistentQueue as PersistentQueue
import MailChariot.InboxMonitor as InboxMonitor
from MailChariot import Notifier
from MailChariot.RequestHandler import RequestHandler
from MailChariot.SpamAssassin import SpamAssassin

parser = argparse.ArgumentParser(description =
        'Filter mail through a spam filter.')
parser.add_argument('-j', '--jobs', dest = 'jobs', type = int, default = 1,
        help = 'run this many worker threads')
parser.add_argument('--version', '-v',
        version = 'MailChariot {0}'.format(VERSION), action = 'version')
args = parser.parse_args()

conf_path = os.path.join(os.environ['HOME'], '.MailChariot.conf')

def sigint_handler(signal, frame):
    print('SIGINT caught, will clean up and exit.')
    Notifier.notify()

signal.signal(signal.SIGINT, sigint_handler)
signal.siginterrupt(signal.SIGINT, False)

try:
    conf = Configuration.Reader(conf_path)
except:
    print('Configuration file "{0}" is broken.'.format(conf_path))
    sys.exit(1)

SpamAssassin.configure(conf)

queue = PersistentQueue.open(conf.queue)
def get_monitor(path, name, format):
    if format == 'mbox':
        return InboxMonitor.mbox(path, queue, name)
    elif format == 'Maildir':
        return InboxMonitor.Maildir(path, queue, name)
    else:
        raise 'Unsupported mailbox format {0}.'.format(format)

inbox_monitor = Thread(target = get_monitor(conf.inbox, 'inbox',
    conf.inbox_format))
mark_ham = Thread(target = get_monitor(conf.notspam, 'mark_ham',
    conf.notspam_format))
mark_spam = Thread(target = get_monitor(conf.notham, 'mark_spam',
    conf.notham_format))
request_handlers = []
for i in range(args.jobs):
    request_handlers.append(Thread(target = RequestHandler(conf, queue)))
inbox_monitor.start()
mark_ham.start()
mark_spam.start()
for i in range(args.jobs):
    request_handlers[i].start()
# Signals are not delivered through join, so we have to sleep as everyone
# else.
while Notifier.sleep(60):
    pass
inbox_monitor.join()
mark_spam.join()
mark_ham.join()
for i in range(args.jobs):
    request_handlers[i].join()
