#!/bin/sh
#
#  Copyright (C) 2010, 2011, 2012, 2013, 2014 Free Software Foundation, Inc.
#
#  This file is part of GNU ease.js.
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.
# #

PATH_TOOLS=$( dirname "$0" )
PATH_LIB="$PATH_TOOLS/../lib"
PATH_TEST="$PATH_TOOLS/../test"
MODULE_EXT='js'
TPL_PATH="$PATH_TOOLS/combine.tpl"
TPL_LICENSE_PATH="$PATH_TOOLS/license.tpl"
TPL_TEST_PATH="$PATH_TOOLS/combine-test.tpl"
TPL_VAR='/**{CONTENT}**/'
RMTRAIL="$PATH_TOOLS/rmtrail"

# determine the order in which modules must be concatenated; order matters to
# ensure dependencies are loaded before the module that depends on them
cat_modules=$(
    cd "$PATH_TOOLS/../" &&
    grep -rIo ' require(.*)' lib/ \
        | sed "s/^lib\///;s/\.js://;s/require(.*'\/\(.*\)'.*/\1/" \
        | node tools/combine-order.js
) || {
    echo "Failed to get module list" >&2
    exit 3
}

# get a list of all available modules
all_modules=$(
    cd "$PATH_LIB" &&
    ls -1 *.js \
    | sed 's/\.js$//'
)

# get lsit of modules that haven't been
remain_modules=$(
    echo "$cat_modules
$all_modules" \
    | sort \
    | uniq -u
)

cat_modules="$cat_modules
$remain_modules"

##
# Output template header
##
tpl_header()
{
    # prepend license
    cat "$TPL_LICENSE_PATH"

    # cut out the top of the template (before the content location)
    cat "$TPL_PATH" \
        | awk "{
            if ( \$0 == \"$TPL_VAR\" )
                exit;
            else
                print \$0;
        }"
}

##
# Output template footer
##
tpl_footer()
{
    # cut out the bottom of the template (after where we need to place the
    # content)
    cat "$TPL_PATH" \
        | awk "BEGIN { go = 0 }
        {
            if ( \$0 == \"$TPL_VAR\" )
                go = 1
            else
                if ( go == 1 )
                    print \$0;
        }"
}

# ensure we can locate our templates (should be in the /tools dir)
if [ ! -f "$TPL_PATH" ]; then
    echo "Error: combine.tpl not found ($TPL_PATH)" >&2
    exit 1
fi
if [ ! -f "$TPL_PATH" ]; then
    echo "Error: license.tpl not found ($TPL_PATH)" >&2
    exit 1
fi


# output combined file header
tpl_header

# output each of the modules
for module in $cat_modules; do
    filename="$PATH_LIB/$module.$MODULE_EXT"

    if [ ! -f "$filename" ]; then
        echo "Error: module $module not found ($filename)" >&2
        exit 2
    fi

    # each module must be enclosed in a closure to emulate a module
    echo "/** $module **/"
    echo "( function( module, __dirname )"
    echo "{"
    echo "    var exports = module.exports = {};"

    # add the module, removing trailing commas
    cat $filename | $RMTRAIL

    echo "} )( module['$module'] = {}, '.' );"
done

# include tests?
if [ "$INC_TEST" ]; then
    # note that not all tests are included
    TEST_CASES=$( cd "$PATH_TEST"; find . -name '*Test*.js' \
        | sed 's/^.\///' \
        | sort \
        | grep -v '\(Combine\(PreEs5\)\?\|Index\)Test.js' \
    )

    # find include files separately so we can output those before the tests
    TEST_INC=$(
        cd "$PATH_TEST" \
            && find . -name 'inc-*.js' \
            | sed 's/^\.\///' \
    )

    # include test combine template
    cat "$TPL_TEST_PATH" | grep -v '^#' | $RMTRAIL

    echo "/** TEST CASES **/"
    echo "ns_exports.runTests = function()"
    echo "{"

    for testcase in $TEST_INC $TEST_CASES; do
        filename="$PATH_TEST/$testcase"

        # generate the module name by removing path and extension, then
        # prefixing it with "test/"
        module="${filename%.*}"
        module="test/${module##*test/}"
        module_dir=$( dirname "$module" )

        # each module must be enclosed in a closure to emulate a module
        echo "/** TEST CASE: $testcase **/"
        echo "( function( module, __dirname )"
        echo "{"
        echo "    var exports = module.exports = {};"

        # write out current test to make debugging easier in browsers with very
        # little debugging support
        echo "    document.write( '$module...<br />' )"

        # add the module, removing trailing commas
        cat $filename | $RMTRAIL

        echo "} )( module['$module'] = {}, '$module_dir' );"
    done

    echo "};"
fi

# output combined file footer
tpl_footer

exit 0

