#!/usr/bin/env python3

import markdown
import pathlib
import sys
import re
import glob

def print_usage():
    print("\nusage: python feed.py ROOT\n")
    print("\n")
    print("\t\ROOT\tbase folder")

def validate():
    # check args for at least one file path
    if len(sys.argv) < 2:
        print_usage()
        sys.exit(1)

validate()

base_folder = sys.argv[1]

def get_paths() -> [str]:
    return [x for x in glob.glob(f"{base_folder}/*.md")]

def get_text(path):
    with open(path) as f:
        return f.read()

#def to_html(md : str) -> str:
#    return markdown.markdown(md, extensions=["fenced_code"])

def get_entry(path):
    return get_title(get_text(path))

def get_title(md):
    return re.compile(r"^# (.+)\n").match(md).group(1)

def get_entries() -> [str]:
    return "\n\n".join([get_entry(p) for p in get_paths()])

def get_header() -> str:
    return """<?xml version="1.0" encoding="utf-8" ?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
<channel>
    <title></title>
    <link>https://ktyl.dev/garden</link>
    <description></description>
    <atom:link href="https://ktyl.dev/garden/feed.xml" rel="self" type="application/rss+xml"/>
"""

def get_footer() -> str:
    return "\n</channel></rss>"

print(get_header())
print(get_entries())
print(get_footer())
