#!/usr/bin/perl -w

# This script will combine all "global" JavaScript source not associated with
# a scene in the sources.json file into a single JavaScript source file.
# It will also write to stdout a modifed sources.json formatted file to
# refer to this file - removing existing global JavaScript references.

use strict;

my $source = '';
my $scenes = '';
my %sourceSceneMap;
my @sources;
my $allFiles = 0; # Combine all files (even scene mapped files) into a single source file.

# Read from stdin a sources.json file building a map of its contents.
while (<>) {
	if (m/source":\s+"([^"]+\.js)"/) {

		$source = $1;
		$source =~ s|\\||g;
		if ($source ne '') {
			push @sources, $source;
		}
	}
	elsif (m/"scenes":\s+(.+)$/) {
		$scenes = $1;
		$sourceSceneMap{$source} = $scenes if not $allFiles;
	}
}

# Concatenate all global JavaScript code
my $globalCode = 'app/controllers/global_code.js';
unlink $globalCode;
foreach my $s (@sources) {
	if ( $allFiles or not exists $sourceSceneMap{$s} ) {
		`cat $s >> $globalCode`;
	}
}

# Now write out the new sources.json file
print "[\n";
print " {\n";
print '  "source": "app\/controllers\/global_code.js"', "\n";
print " }";

foreach my $s (@sources) {
	if ( exists $sourceSceneMap{$s} ) {
		$scenes = $sourceSceneMap{$s};
		$s =~ s|/|\\/|g;
		print ",\n {\n";
		print "  \"source\": \"$s\",\n";
		print "  \"scenes\": $scenes\n";
		print " }";
	}
}

print "\n]\n";
