#!/usr/bin/env ruby
require 'fileutils'
require 'json'
require 'pry'

topics = []
# TODO: build in parallel

# extract latex portion of files
Dir.glob("content/*.md") do |mdfile|

	# only process files with LaTeX block
	next unless File.readlines(mdfile).grep(/[`][`][`]latex/).any?

	title = mdfile.gsub("content/", "").gsub(".md", "")
	topics.push(title)

	img_base = "."

	pngfile = "#{img_base}/img/#{title}.png"
	pngfile_colorblind = "#{img_base}/img/#{title}-colorblind-assist.png"

#	binding.pry

	# only rebuild when source newer than output. If preamble changes, touch all source files.
	if File.exist?(pngfile) and File.mtime(mdfile) < File.mtime(pngfile)
		puts "Skipping #{mdfile}"
		next
	else
		puts "Rebuilding #{mdfile}"
	end

	# extract embedded latex
	cmd = "awk '/```latex/ {p=1}; p; /```($|\s)/ {p=0}' \"#{mdfile}\" | egrep -v '```' > tex/input.tex"
	puts cmd
	system(cmd)

	# build regular png
	cmd = "cd tex; cp preamble-default.tex preamble.tex; ./build.sh; cp output.png \"../#{pngfile}\""	
	puts cmd
	system (cmd)

	# build colorblind png
	cmd = "cd tex; cp preamble-colorblind-assist.tex preamble.tex; ./build.sh; cp output.png \"../#{pngfile_colorblind}\""	
	puts cmd
	system (cmd)
end

# save topics to file for local dev
File.open("content/.vuepress/topics.js", 'w') {|f| f.write("var TOPICS = #{topics.to_json};\nmodule.exports.TOPICS = TOPICS;\n")}
