#!/usr/bin/env python3
# ***************************************************************************
#  IIIIII NNN  NNN  Copyright (C) 2022 Innovative Networks, Inc.
#    II    NNN  N   All Rights Reserved. Any redistribution or reproduction
#    II    N NN N   of part or all of the content of this program in any form
#    II    N  NNN   without expressed written consent of the copyright holder
#  IIIIII NNN  NNN  is strictly prohibited.  Please contact admins@in-kc.com
#   Be Innovative.  for additional information.
# ***************************************************************************
#  check_uap_disk.py
#  Author - Ian Perry <iperry@indigex.com>
#
#  Purpose:  Checks imap for a given mailbox
#
#  Version History:
#       2022.11.08 - Initial Creation
# ***************************************************************************
try:
    from inmon_utils import *
except:
    import sys
    print("Failed to import inmon_utils")
    sys.exit(3)

import argparse
import logging
import imaplib

parser = argparse.ArgumentParser(description="Checks imap for a given mailbox")

parser.add_argument(
    '-H', '--hostname',
    dest='hostname',
    help='Server to log into',
    default='localhost'
)

parser.add_argument(
    '-p', '--port',
    dest='port',
    help='Port to be used for IMAP'
)

parser.add_argument(
    '-P', '--password',
    dest='password',
    help='Password to log into mailbox with',
    required=True
)

parser.add_argument(
    '-u', '--username',
    dest='username',
    help='Mailbox to log into',
    required=True
)

parser.add_argument(
    '-s', '--subject',
    dest='subject',
    help='Subject to search for',
    required=True
)

parser.add_argument(
    '-f', '--from',
    dest='from_addr',
    help='Address message was sent from',
    required=True
)

parser.add_argument(
    '-S', '--ssl',
    dest='use_ssl',
    help='Use SSL',
    action='store_true'
)

parser.add_argument(
    '-d', '--debug',
    dest='debug',
    help='Enable debugging output',
    action='store_true'
)

args = parser.parse_args()

# Assign port
if args.port is None:
    if args.use_ssl:
        port = 993
    else:
        port = 143
else:
    port = args.port

if args.debug:
    log_level = "DEBUG"
else:
    log_level = "WARN"

log_level = getattr(logging, log_level.upper())
logging.basicConfig(level=log_level)
logger = logging.getLogger()

logger.debug(f"""
    Hostname: {args.hostname}
    Username: {args.username}
    Password: {args.password}
    Subject: {args.subject}
    Port: {port}
    Use SSL: {args.use_ssl}
""")

try:
    if args.use_ssl:
        con = imaplib.IMAP4_SSL(args.hostname, port=port)
    else:
        con = imaplib.IMAP4(args.hostname, port=port)
except Exception as e:
    print(f"[CRITICAL] - Unable to connect to server {args.hostname} on {port}: {e}")
    sys.exit(2)

try:
    con.login(args.username, args.password)
except Exception as e:
    print(f"[CRITICAL] - Unable to log into mailbox {args.username}: {e}")
    sys.exit(2)

con.select()
resp, data = con.search(None, 'SUBJECT', f'"{args.subject}"', 'FROM', f'"{args.from_addr}"')
email_ids = data[0].split()
for num in email_ids:
    con.store(num, '+FLAGS', '\\Deleted')

try:
    resp, data = con.expunge()
    if data[0] is None:
        emails_deleted = 0
    else:
        emails_deleted = len(data)
except Exception as e:
    print(f"[CRITICAL] - Unable to expunge emails: {e}")
    sys.exit(2)

if len(email_ids) == emails_deleted and emails_deleted > 0:
    print(f"[OK] - {len(email_ids)} found, {emails_deleted} deleted.")
    sys.exit(0)
elif len(email_ids) > emails_deleted:
    print(f"[CRITICAL] - {len(email_ids)} found, {emails_deleted} deleted.")
    sys.exit(2)
elif len(email_ids) == 0:
    print(f"[CRITICAL] - 0 emails found.")
    sys.exit(2)
else:
    print(f"[UNKNOWN] - Something weird happened.")
    sys.exit(3)

