#!/usr/bin/python3
import sys
import os
import mailbox
from urllib.parse import unquote, urlencode
import re
from email.header import Header, decode_header, make_header
import gemini

def gen_summary(filename, message_id=None):
    mbox = mailbox.mbox(filename)
    path = os.environ['SCRIPT_NAME'] if 'SCRIPT_NAME' in os.environ else ""

    # reverse the order of messages in the main list
    main_list = message_id == None or len(message_id) == 0
    msgs = mbox
    if main_list:
        msgs = []
        for m in mbox:
          msgs.insert(0, m)
    else:
       print("=>", path, "Back to topic list", "\n")

    replies = [ message_id ]
    for message in msgs:
       try:
          subject = str(make_header(decode_header(message['subject'])))
       except:
          subject = message['subject']

       # display the main message list (main topics)
       if main_list and 'in-reply-to' not in message and 'references' not in message:
          id = urlencode({"id": message['message-id']})
          print("=>", path + "?" + id, subject)

       # display the message thread if a message_id is specified
       references = message['references'] if message['references'] else ""
       if not main_list and (message['in-reply-to'] in replies or references.find(message_id) >= 0 or message['message-id'] == message_id):
          replies.append(message['message-id'])

          if message['message-id'] == message_id:
              print("##", subject)

          print("###", message['date'], str(make_header(decode_header(message['from']))))
          print("\n")
          cleanr = re.compile('\>.*\n')
          body = re.sub(cleanr, '.', message.get_payload())
          body = gemini.escapeGemini(body)
          body = gemini.linkify(body)
          print(body)
          print("\n=> mailto:gemini@lists.orbitalfox.eu?" + urlencode({"Subject:": subject}) + "&" + urlencode({"In-Reply-To": message['message-id']}), " Reply to post")

print("20 text/gemini")

if "QUERY_STRING" in os.environ and len(os.environ['QUERY_STRING']) > 0:
   gen_summary("/var/gemini/2021.txt", unquote(os.environ['QUERY_STRING'])[3:])
else:
   print("# Gemini mailing list archive, 2021", "\n")
   print("________________________________________\n")
   print("Updated once a day")
   print("=> https://lists.orbitalfox.eu/archives/gemini/ Original mailing list archive")
   print("=> gemini://rawtext.club/~sloum/geminilist/ Another viewer of Gemini mailing list", "\n")
   print("________________________________________\n")

   print("\n=> mailto:gemini@lists.orbitalfox.eu Post new topic\n")
   gen_summary("/var/gemini/2021.txt")

