#!/usr/bin/env python3
from glob import glob
import subprocess as sp
import sys, os, os.path

month_short = [
   "Jan", "Feb", "Mar", "Apr", "May", "Jun",
   "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
   ]

base = "/users/aiwein"

def loadvars(path):
   vars = {}
   with open(path, "r") as f:
       for line in f:
           if line.startswith(".SET"):
               _, k, v = line.strip().split(maxsplit=2)
               vars[k] = v
           elif line.startswith(".INIT"):
               break
   return vars

if len(sys.argv) < 3:
   print("Usage: %s INDIR OUTDIR" % sys.argv[0])
   exit(1)
else:
   indir = sys.argv[1]
   outdir = sys.argv[2]
   varfile = os.path.join(indir, "vars.tr")
   if os.path.isfile(varfile):
       gvars = loadvars(varfile)
       base = gvars.get("base", base)

def loadtext(path):
   text = ""
   with open(path) as f:
       write = False
       for line in f:
           if "# post - end" in line:
               break
           elif "# post - start" in line:
               write = True
           elif write:
               text += line
   return text

# Last year, last_month
l_y, l_m = "9999", "99"
years = []
# Main gophermap, year gophermap
os.makedirs(outdir, exist_ok=True)
main, year_f = open(os.path.join(outdir, "gophermap"), "w"), None
# Get the files
files = sorted(glob(os.path.join(indir, "*.txt")), reverse=True)
# Process everything
main.write("!Phlog\n")
main.write("# nav - start\n")
main.write("1Home\t%s\n" % (base))
main.write("# nav - end\n")
main.write("\n")
for i, path in enumerate(files):
   bare, ext = os.path.splitext(os.path.basename(path))
   year, month, day = bare.split("-")
   # TODO Check whether the gophermap exists, and, if it does,
   # whether it's newer than our source file.  If it is, or if it
   # doesn't exist, do whatever is needed to generate it.
   gopherdir = os.path.join(outdir, year, month, day)
   gophermap = os.path.join(gopherdir, "gophermap")
   # Load any interesting variables from the source file
   vars = loadvars(path)
   # Create the necessary directories
   os.makedirs(gopherdir, exist_ok=True)
   # Generate the gophermap
   sp.call(["./gen-page.sh", path, gophermap])
   # Latest N post, embed them in full
   if i < 5:
       main.write("1== %s %s ==\t%s\n" % (
           bare, vars.get("title", ""), bare.replace("-", "/")))
       text = loadtext(gophermap)
       main.write(text)
       # If it's the latest post, also write it out to its own file
       # to make embedding it easy.
       if i == 0:
           with open(os.path.join(outdir, "latest"), "w") as f:
               f.write("1%s %s\t%s\n" % (
                   bare, vars.get("title", ""),
                   os.path.join(outdir, year, month, day)))
               f.write(text)
   # We changed year: start generating the gophermap for the archive
   if year < l_y:
       if year_f is not None:
           year_f.close()
       year_f = open(os.path.join(outdir, year, "gophermap"), "w")
       years.append(year)
       year_f.write("!%s\n" % year)
       year_f.write("# nav - start\n")
       year_f.write("1Home\t%s\n" % base)
       year_f.write("1Back to phlog\t%s\n" % os.path.join(base, outdir))
       year_f.write("# nav - end\n")
       l_y, l_m = year, "99"
   # We changed month: add a new header to the year's gophermap
   if month < l_m:
       year_f.write("\n")
       year_f.write("i== %s %s ==\t\n" % (
           year, month_short[int(month)-1]))
       l_m = month
   # Write a link to this post to its year's gophermap
   year_f.write("1%s %s\t%s/%s\n" % (
       bare, vars.get("title", ""), month, day))
main.write("\ni== Archive ==\t\n")
for year in years:
   main.write("1%s\t%s\n" % (year, year))
main.close()