#!/usr/bin/python
# -*- encoding: utf-8 -*-

# © 2012, David Paleino <dapal@debian.org>

import json
import sys
import os

# the multiple-times copyright statement to remove
copyright_stmt = """/*!
 * Ext JS Library 3.4.0
 * Copyright(c) 2006-2011 Sencha Inc.
 * licensing@sencha.com
 * http://www.sencha.com/license
 */
"""

script = json.load(open(sys.argv[1]))
for pkg in script['pkgs']:
	included_copyright = False
	debug = pkg.get('isDebug', False)
	if debug:
		out = pkg['file'][:-3] + '-debug.js'
	else:
		out = pkg['file']
	print out,
	# make sure the directory exists
	if out.rfind('/') != -1:
		os.system('mkdir -p %s' % out[:out.rfind('/')])
	output = open(out, 'w')

	# only include pkgDeps for ext-all.css and ext-all.js
	if pkg.has_key('pkgDeps') and 'ext-all' in pkg['file']:
		if not pkg.get('includeDeps', True):
			pass
		else:
			# first, dependencies
			for inc in pkg['pkgDeps']:
				if debug:
					inc = inc[:-3] + '-debug.js'
				with open(inc) as f:
					if included_copyright:
						# we already included the copyright statement,
						# drop it.
						s = f.read()
						s = s.replace(copyright_stmt, '')
						output.write(s)
					else:
						output.writelines(f.readlines())
						included_copyright = True

	# then, files to include.
	for inc in pkg['fileIncludes']:
		if inc['text'].endswith('.js'):
			if debug:
				f = inc['path'] + inc['text']
			else:
				f = inc['path'] + inc['text'][:-3] + '-debug.js'				
		else:
			f = inc['path'] + inc['text']

		with open(f) as f:
			if included_copyright:
				# we already included the copyright statement,
				# drop it.
				s = f.read()
				s = s.replace(copyright_stmt, '')
				output.write(s)
			else:
				output.writelines(f.readlines())
				included_copyright = True

	output.close()
	print 'done.'

	if debug:
		# minify
		minout = out.replace('-debug', '')
		print minout,
		os.system('yui-compressor -o %s %s' % (minout, out))
		print 'minified OK.'
