Just so I remember this in case I ever need it again

# This script assumes it's launched from inside the micro.blog export folder

import frontmatter
import os
import re
import shutil
from dateutil import parser

basedir = '/Users/jem/Desktop/TestOutput'
imgpat = re.compile('')
domainpat = re.compile('https:.*/uploads/')
blothead = 'title: {}\ndate: {}\n\n'

# I really dislike doing this but ...
imgdata = {'destdir':'',}

def copyimage(src,dest):
    shutil.copy(os.path.join('uploads',src), os.path.join(imgdata['destdir'],dest))
    
def imgproc(m):
    orgpath = m.group(1)
    
    # Remove domain info
    p = domainpat.sub('',orgpath)
    n = '_'+os.path.basename(p)
    copyimage(p,n)
    return '![]('+n+')'

def formatblotpost(post):
    # Update content and copy image files
    modifiedcontent = imgpat.sub(imgproc,post.content)
    if post.metadata['title'] == '':
        post.metadata['title'] = post.metadata['datetitle']
    return blothead.format(post.metadata['title'],post.metadata['date']) + modifiedcontent
        
def create_destdir(newbase,curfilepath,poststamp):
    (odir,oname) = os.path.split(curfilepath)
    newdir = os.path.join(newbase,odir)
    # Check if the dest dir exists, this should be the year & month folder
    if not os.path.isdir(newdir):
        os.makedirs(newdir)
    postdir = os.path.join(newdir,poststamp)
    # This should not be possible but ...
    if os.path.isdir(postdir):
        raise Exception('Post dir already exists')
    else:
        os.mkdir(postdir)
    return postdir

def handlepost( destdir, source ):
    print(source)
    
    try:
        postcontent = frontmatter.load(source)
        meta = postcontent.metadata
        pdate = parser.parse(meta['date'])
        pdir = create_destdir(destdir,source,pdate.strftime('%Y%m%d_%H%M%S'))
        postcontent['datetitle']= pdate.strftime('%Y-%m-%d %H:%M:%S')
        # Deep sigh
        imgdata['destdir'] = pdir

        # Create actual post
        of = open(os.path.join(pdir,'index.md'),'w')
        of.write(formatblotpost(postcontent))
        of.close()
    except FileNotFoundError as arg:
        print(arg)

for root, dirs, files in os.walk('.'):
    if not 'uploads' in root:
        for f in files:
            if not '.DS_Store' in f:
                handlepost(basedir,os.path.join(root,f))