#!/usr/bin/env python3

from imaplib import IMAP4_SSL
from subprocess import check_output
from sys import argv, exit
from time import time

if len(argv) < 5:
    print('Usage: {} <imap host> <username> <password> <message sender>'.format(argv[0]))
    exit(3)

NOW = time()

try:
    imap = IMAP4_SSL(argv[1])
    imap.login(argv[2], argv[3])

    imap.select('Inbox')

    _, data = imap.search(None, 'ALL')

    something_found = False

    for item in data:
        for index in item.split():
            received_in_this_mail = None
            from_in_this_mail = False

            try:
                message = imap.fetch(index, '(RFC822)')

                message_text = bytearray()
                for part in message[1][0]:
                    message_text.extend(part)
                message_text = message_text.decode().splitlines()

                for line in message_text:
                    lline = line.strip().lower()

                    if lline.startswith('from:') and argv[4].lower() in line:
                        from_in_this_mail = True

                    if lline.startswith('date:'):
                        date = line.strip()[5:].strip()
                        unixtime = int(check_output([
                            'date',
                            '--date={}'.format(date),
                            '+%s',
                        ]).decode().strip())

                        if unixtime > (NOW-(60*60*25)):
                            received_in_this_mail = date

                    if received_in_this_mail and from_in_this_mail:
                        print('Found message from "{}" sent at "{}"'.format(argv[4], received_in_this_mail))
                        received_in_this_mail = None
                        from_in_this_mail = False
                        something_found = True
            except:
                pass

    if  something_found:
        # there should be output above
        exit(0)

    print('No Mails found')
    exit(2)
except Exception as e:
    print(repr(e))
    exit(3)