#!/usr/bin/env python3
#
# makegallery.py - creates a hugo gallery out of a series of directories and subdirectories
#

template = '''---
categories: ["Photos"]
date: "{{date}}"
title: "{{title}}"
url: {{url}}
author: marco
excludeFromIndex: true
summary: Imported Photo Album
---

{{for up}}[Up ({{upp}})]({{upurl}})

{{end up}}{{for child}}* [{{cname}}]({{curl}})
{{end child}}

{{< gallery dir="{{location}}" />}} {{< load-photoswipe >}}'''

import argparse
p = argparse.ArgumentParser()
p.add_argument('-d', '--dir', default='./static/photos')
p.add_argument('-p', '--post', default='./content/photos')
o = p.parse_args()

import os.path
if not os.path.isdir(o.dir):
  print(f"Directory {o.dir} is not a directory. Giving up")
  exit()
if not os.path.isdir(o.post):
  print(f"Directory {o.post} is not a directory. Giving up")
  exit()

def pretty(s):
  return os.path.basename(s).replace('_', ' ').title()

def jinja(dic):
  out = template
  for key, val in dic.items():
    if type(val) == list:
      outlist = []
      exp = "\{\{for "+key+"\}\}(.*)\{\{end "+key+"\}\}"
      rep = re.search(exp, out, re.DOTALL)
      if not rep:
        continue
      for item in val:
        stemplate = rep.group(1)
        for skey in sorted(item.keys()):
          sval = item[skey]
          stemplate = stemplate.replace("{{" + skey + "}}", sval)
        outlist.append(stemplate)
      out = out.replace(rep.group(), "".join(outlist))
    else:
      out = out.replace("{{" + key + "}}", val)
  return out

def geturl(d):
  return re.sub("^.*/static", "", d)

import os, re, datetime
today = datetime.date.today().isoformat()
def build(d):
  for root, dirs, files in os.walk(d):
    rootname = pretty(root)
    fname = geturl(root)[1:].replace("/", "_") + ".md"
    parent = os.path.dirname(root)
    when = re.search('20..-..-..', root)
    if not when:
      when = re.search('20[0-9][0-9]', root)
    if when:
      when = when.group()
      if len(when) == 4:
        if today[:4] == when:
          when = today
        else:
          when += "-12-31"
    if not when:
      when = "2000-01-01"
    loc = geturl(root)
    if root == o.dir:
      up = []
    else:
      up = [{"upp": pretty(parent), "upurl": geturl(parent)}]
    with open(os.path.join(o.post, fname), 'w') as f:
      f.write(jinja({
        "date": when,
        "title": rootname,
        "location": loc,
        "url": geturl(root),
        "up": up,
        "child": [{"curl": geturl(os.path.join(root,d)), "cname": pretty(d)} for d in sorted(dirs)]
        }))
    for d in dirs:
      build(d)

build(o.dir)
