#!/usr/bin/python3 -u
import os
import sys
import subprocess
import xml.etree.ElementTree as ET

def log(msg):
    with open('/tmp/exim_queue_plugin.log', 'a') as f:
        f.write(f"[{__import__('datetime').datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] {msg}\n")

def parse_queue_output(output):
    messages = []
    lines = output.split('\n')
    i = 0
    while i < len(lines):
        line = lines[i].strip()
        if not line or 'Exim' in line or 'Total' in line:
            i += 1; continue
        parts = line.split()
        if len(parts) >= 4 and '-' in parts[2] and len(parts[2]) > 10:
            msg_id = parts[2]
            sender = ""
            for part in parts[3:]:
                if part.startswith('<') and part.endswith('>'):
                    sender = part.strip('<>'); break
            recipient = ""
            if i + 1 < len(lines):
                next_line = lines[i + 1].strip()
                if next_line and '@' in next_line:
                    recipient = next_line.split()[0].strip('<>')
            messages.append({
                'id': msg_id, 'age': parts[0], 'size': parts[1],
                'sender': sender if sender else 'N/A',
                'recipient': recipient if recipient else 'N/A'
            })
            i += 2
        else:
            i += 1
    return messages

def get_queue():
    result = subprocess.run(['exim', '-bp'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=10)
    if result.returncode != 0: return []
    return parse_queue_output(result.stdout)

def delete_messages(msg_ids):
    log(f"DELETE: {msg_ids}")
    subprocess.run(['exim', '-Mrm'] + msg_ids, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=30)

def deliver_messages(msg_ids):
    log(f"DELIVER SELECTED: {msg_ids}")
    for msg_id in msg_ids:
        subprocess.run(['exim', '-M', msg_id], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=30)

def deliver_all():
    log("DELIVER ALL: exim -qff")
    subprocess.run(['exim', '-qff'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=60)

try:
    PARAM_elid = os.environ.get('PARAM_elid', '')
    PARAM_func = os.environ.get('PARAM_func', 'exim_queue')
    PARAM_sok = os.environ.get('PARAM_sok', '')
    PARAM_clicked_button = os.environ.get('PARAM_clicked_button', '')
    REQUEST_METHOD = os.environ.get('REQUEST_METHOD', 'GET')
    
    # После Yes в форме deliver_all — выполняем и возвращаем ok
    if PARAM_sok == 'ok' and PARAM_func == 'exim_queue' and PARAM_clicked_button == 'ok':
        deliver_all()
        root = ET.Element('doc', {'func': 'exim_queue'})
        ET.SubElement(root, 'ok')
        print(ET.tostring(root, encoding='unicode'))
    # Форма подтверждения
    elif PARAM_func == 'exim_queue.deliver_all':
        print('<?xml version="1.0" encoding="UTF-8"?>')
        print('<doc func="exim_queue">')
        print('<metadata type="form">')
        print('<form>')
        print('<field name="info"><textdata name="info"/></field>')
        print('<buttons>')
        print('<button type="ok" name="ok">Yes</button>')
        print('<button type="cancel" name="cancel">No</button>')
        print('</buttons>')
        print('</form>')
        print('</metadata>')
        print('<info>Deliver ALL messages in queue? This will force delivery of all messages.</info>')
        print('<messages>')
        print('<msg name="title">Deliver All Messages</msg>')
        print('<msg name="info"> </msg>')
        print('<msg name="msg_ok">Yes</msg>')
        print('<msg name="msg_cancel">No</msg>')
        print('</messages>')
        print('</doc>')
    # Групповые операции
    elif REQUEST_METHOD == 'POST' and PARAM_elid:
        if PARAM_func == 'exim_queue.delete':
            delete_messages([x.strip() for x in PARAM_elid.split(',') if x.strip()])
        elif PARAM_func == 'exim_queue':
            deliver_messages([x.strip() for x in PARAM_elid.split(',') if x.strip()])
        root = ET.Element('doc', {'func': 'exim_queue'})
        ET.SubElement(root, 'ok')
        print(ET.tostring(root, encoding='unicode'))
    # Показ очереди
    else:
        stdin_data = sys.stdin.read()
        root = ET.fromstring(stdin_data) if stdin_data.strip() else ET.Element('doc', {'func': 'exim_queue'})
        for m in get_queue():
            elem = ET.SubElement(root, 'elem')
            for field in ['id', 'age', 'size', 'sender', 'recipient']:
                child = ET.SubElement(elem, field)
                child.text = m[field]
        print(ET.tostring(root, encoding='unicode'))

except Exception as e:
    log(f"ERROR: {e}")
    root = ET.Element('doc', {'func': 'exim_queue'})
    error = ET.SubElement(root, 'error')
    msg = ET.SubElement(error, 'msg', {'name': 'body'})
    msg.text = str(e)
    print(ET.tostring(root, encoding='unicode'))
