#!/bin/sh
# vim: syntax=:ts=8

set -ex

printf '%s: Current working directory is %s.\n' "$0" "$PWD"

<"$0".content python3 -c '
import os, sys
class File:
	attributes = []; content = ""; substitutions = dict()
	figurative = True; stub = True
	def addattribute(self, *args):
		for a in args: # sloppy but works
			if a == "stub":          	self.stub = True
			elif a == "verbatim":    	self.stub = False
			elif a == "figuratively":	self.figurative = True
			elif a == "literally":   	self.figurative = False
	def __init__(self, **kwargs):
		for key in kwargs:
			if key == "attributes":	self.addattribute(*kwargs[key])
			else:	setattr(self, key, kwargs[key])
files = dict()
for part in reversed(sys.stdin.read().split("\n\n\n")[1:]):
	name = "." + part.split("\n")[0]
	if "\t" in "." + name:
		attributes = name.split("\t")[1].split(",")
		name = name.split("\t")[0]
	else:	attributes = []
	if len(name) <= 1 or name[1] != "/" or "ignore" in attributes:
		continue
	content = part.split("\n\n")[0].split("\n")
	substitutions = dict()
	if(len(content) > 1):
		for s in content[1:]:
			s = s.split("\t")
			if len(s) == 2: substitutions[s[0]] = s[1]
	mode = "replace"
	for attribute in attributes:
		if attribute in ["append", "replace"]:
			mode = attribute
	attributes = list(set(attributes) ^ {"append", "replace"})
	content = part[len("\n".join(content))+2:]
	file = File(attributes = attributes, content = content + "\n",
		substitutions = substitutions)
	if mode == "append":
		if not(name in files):
			sys.stderr.write(sys.argv[0] + ": " + name + ": "
				+ "appending to nothing\n")
		else:
			file.content = files[name].content + file.content
	files[name] = file
for name in files:
	if files[name].stub:
		p = ""; s = ""; d = name
		while True:
			d = os.path.dirname(d)
			if (p == ""
					and os.path.join(d, "Prefix")
						in files.keys()):
				p = files[os.path.join(d, "Prefix")].content
			if (s == ""
					and os.path.join(d, "Suffix")
						in files.keys()):
				s = files[os.path.join(d, "Suffix")].content
			if d == "." or (not(p == "") and not(s == "")):
				break
		files[name].content = p + files[name].content + s
	if files[name].figurative:
		content = files[name].content
		for s in files[name].substitutions:
			instances = []
			i = 0
			while True:
				instance = content.find(s, i)
				if instance == -1:	break
				instances += [instance]
				i = instance + len(s)
			if len(instances) == 0:	continue
			for i in reversed(instances):
				content = (content[:i]
					+ files[name].substitutions[s]
					+ content[i+len(s):])
		files[name].content = content
	# TODO error checking
	if not(os.path.isdir(os.path.dirname(name))):
		os.makedirs(os.path.dirname(name))
	with open(name, "w") as fd:	fd.write(files[name].content)
d = ""; bucket = "#!/bin/sh\n"
for name in files:
	d = name
	while True:
		if os.path.dirname(d) == ".":
			mop = ("rm "
				+ "-r " * os.path.isdir(d)
				+ name # yeah this sucks
				+ "\n"
			)
			if not(mop in bucket):	bucket += mop
			break
		else:
			d = os.path.dirname(d)
if len(bucket.split("\n")) > 2:
	with open("./cleanup.sh", "w") as fd:
		fd.write(bucket)
'
test -x "$0".local \
	&& exec ./"$0".local \
	|| test -e "$0".local \
		&& exec sh "$0".local \
	|| exit 0
