#! /usr/bin/env python

################################################
# Convert a few Junicode symbols to PDF files. #
#                                              #
# In fact, this script creates only a Ninja    #
# build file to perform the conversion.        #
#                                              #
# Author: Scott Pakin <scott-clsl@pakin.org>   #
################################################

import glob
import os
import re
import subprocess
import sys


def kpsewhich(fname):
    'Find a filename in the TeX tree.'
    proc = subprocess.run(['kpsewhich', fname], capture_output=True,
                          check=True, encoding='utf-8')
    return proc.stdout.strip()

def header_string():
    'Return a "generated file" header string.'
    full_name = os.path.abspath(sys.argv[0])
    gen_line = 'This is a generated file.  DO NOT EDIT.'
    edit_line = f'Edit {full_name} instead.'
    max_chars = max(len(gen_line), len(edit_line))
    hash_line = '#' * (max_chars + 4)
    return '\n'.join([
        hash_line,
        '# %-*.*s #' % (max_chars, max_chars, gen_line),
        '# %-*.*s #' % (max_chars, max_chars, edit_line),
        hash_line,
        '',
    ])

# If we don't have Junicode-Regular.otf, generate a trivial Ninja file
# and exit.
font_path = kpsewhich('Junicode-Regular.otf')
if font_path == '':
    with open('junicode.ninja', 'w') as w:
        w.write(header_string())
        w.write('''
rule mkdir
  command = mkdir -p $out

build junicode : mkdir
build JUNICODE : phony junicode
''')
    sys.exit(0)

# Generate a Ninja file that builds PDFs for the desired characters.
with open('junicode.ninja', 'w') as w:
    w.write(header_string())
    w.write('''
rule extract-junicode-chars
  command = $
    cd junicode ; $
    fontforge -script ../$in ../$font $chars
  description = Generating EPS files for these Junicode characters: $chars

build junicode/u2123.eps junicode/u211F.eps : extract-junicode-chars unicode2eps.pe | Junicode-Regular.otf
  font = Junicode-Regular.otf
  chars = 0x2123 0x211F

rule eps-to-pdf
  command = epstopdf $in $out
  description = Converting $in to $out

build junicode/u2123.pdf : eps-to-pdf junicode/u2123.eps
build junicode/u211F.pdf : eps-to-pdf junicode/u211F.eps

# COMMONDEPS specifies a dependency on the junicode directory.  If we
# do a "mkdir junicode" here, Ninja will complain that it can't clean
# a non-empty directory.  As a hack, we define junicode as an alias
# for JUNICODE, which is an alias for all files in the junicode/
# directory.
build JUNICODE : phony junicode/u2123.pdf junicode/u211F.pdf
build junicode : phony JUNICODE
''')
