#!/usr/bin/env python3

import argparse
import imapidle
from configparser import ConfigParser
from imaplib import IMAP4, IMAP4_SSL

parser = argparse.ArgumentParser(description='Moves tagged spam into spam folder.')
parser.add_argument('config', help='configuration file')
args = parser.parse_args()

cfg = ConfigParser()
cfg.read(args.config)

host = cfg.get('connection', 'host')
if cfg.getboolean('connection', 'ssl', fallback=False):
	port = cfg.getint('connection', 'port', fallback=993)
	conn = IMAP4_SSL(host, port)
else:
	port = cfg.getint('connection', 'port', fallback=143)
	conn = IMAP4(host, port)

login_user = cfg.get('login', 'user')
login_pass = cfg.get('login', 'pass')
result, _ = conn.login(login_user, login_pass)
assert(result == 'OK')

result, _ = conn.select(cfg.get('folders', 'inbox', fallback='INBOX'))
assert(result == 'OK')

spam_header = cfg.get('headers', 'name', fallback='X-Spam-Tag')
spam_value = cfg.get('headers', 'value', fallback='YES')
spam_folder = cfg.get('folders', 'spam', fallback='Junk')

while True:
	print('Searching')

	result, messages = conn.uid('SEARCH', '(HEADER %s "%s")' % (spam_header, spam_value), '(UNSEEN)')
	assert(result == 'OK')

	uids = messages[0].decode('us-ascii').split()
	for uid in uids:
		print('Moving %s: ' % uid, end='')
		result, _ = conn.uid('MOVE', uid, spam_folder)
		print(result)

	conn.expunge()
	print('Done')

	try:
		for uid, event in imapidle.idle(conn):
			if event == 'EXISTS':
				break
	except KeyboardInterrupt:
		break
	finally:
		imapidle.done(conn)

conn.close()
conn.logout()
