#!/usr/bin/python3
# Regenerate output from a file_list produced by fakewebpack-extract-source-map
#
# Usage: $0 <file_list> <module_list> <extraction directory> > <output>
#

import ast
import os
import shlex
import subprocess
import sys

"""
TODO:
inject-process: 25

"""

JSPROC = os.path.join(os.path.dirname(__file__), "fakewebpack-postprocess.js")

AMD_PREFIX = "define(function() { return "
AMD_SUFFIX = "});"

BOOTSTRAP_PREFIX = "/******/ (function(modules) { // webpackBootstrap"
BOOTSTRAP_LINE_PREFIX = "/******/"
BOOTSTRAP_MODULE_START = """/******/ })
/************************************************************************/
/******/ (["""
BOOTSTRAP_SUFFIX = "/******/ ])"

MODULE_PREFIX_REQ = "/***/ function(module, exports, __webpack_require__) {\n"
MODULE_PREFIX_NOREQ = "/***/ function(module, exports) {\n"
MODULE_LINE_PREFIX = "	"
MODULE_SUFFIX = "/***/ }"

def main(file_list, module_list, srcdir, amd, *args):
	amd = ast.literal_eval(amd)
	mod_idx = 0
	with open(file_list) as fp:
		lines = fp.readlines()
	if amd: print(AMD_PREFIX, end='')
	for f in lines:
		fnn = f.rstrip()
		fn = os.path.join(srcdir, fnn)
		if "webpack/bootstrap" in f:
			print(BOOTSTRAP_PREFIX)
			with open(fn) as rfp:
				for line in rfp.readlines():
					print(BOOTSTRAP_LINE_PREFIX+line, end="")
			print(BOOTSTRAP_MODULE_START)
		else:
			cmdline = ["nodejs",
				os.path.relpath(JSPROC, srcdir),
				fnn,
				os.path.relpath(module_list, srcdir)]
			print("module %02d: %s" % (mod_idx, " ".join(map(shlex.quote, cmdline))), file=sys.stderr)
			print("/* %s */" % mod_idx)
			changed = False
			c = subprocess.check_output(
				cmdline,
				cwd=srcdir).decode("utf-8")
			if c:
				changed = True
			else: # nothing changed, use the plain file
				with open(fn, 'rb') as rfp:
					c = rfp.read().decode("utf-8")
			print(MODULE_PREFIX_REQ if changed else MODULE_PREFIX_NOREQ)
			for line in c.splitlines(keepends=True):
				print(MODULE_LINE_PREFIX+line, end="")
			print()
			print()
			# not off-by-1, len(lines) should be 1+num_modules, including the bootstrap code
			print(MODULE_SUFFIX + ("," if mod_idx < len(lines)-2 else ""))
			mod_idx += 1
	print(BOOTSTRAP_SUFFIX, end='')
	if amd: print(AMD_SUFFIX, end='')
	print(';')

if __name__ == "__main__":
	sys.exit(main(*sys.argv[1:]))
