#!/usr/bin/bash
# -*- coding: utf-8 -*-

import re
import glob
import codecs
import os.path
import argparse

parser = argparse.ArgumentParser("Fix figcaptions in markdownfiles")
parser.add_argument('folder', help="Folder with the bookfolders with markdownfiles")
args = parser.parse_args()

for bookfolder in glob.glob("{0}/book*".format(os.path.normpath(args.folder))):
  for mdpath in glob.glob("{0}/*.md".format(os.path.normpath(bookfolder))):
    mdstring = None

    with codecs.open(mdpath, mode='r', encoding='utf-8') as mdfile:
      mdstring = mdfile.read()
      mdstring = re.sub("<figcaption>", "<span class=\"figcaption\">", mdstring)
      mdstring = re.sub("</figcaption>", "</span>", mdstring)

    if mdstring:
      with codecs.open(mdpath, mode='w', encoding='utf-8') as mdfile:
        mdfile.write(mdstring)