#!/usr/bin/env bash

# Copyright (c) 2013 Thomas Allen <thomas@oinksoft.com>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

# ======================================================================
# goog: Google Closure Tools assets manager and build tool.
#
# usage: goog <command> [options ...]
#
# Commands:
#   build        Build project assets.
#   clean        Clean previously built assets.
#   help         Display help about a command.
#   install      Install the Closure Tools locally.
#   mirror       Set up a mirror that `install' can use.
#   self-test    Run this script's tests. Takes a while!
#   self-update  Replace this script with the latest release from
#                github.
#   skel         Generate a new project skeleton.
# ======================================================================

# ======================================================================
# goog.json: Configure goog.bash.
#
# Options:
# - css-out: Output path for GSS (default: $name.min.css).
# - gss-root: Directory containing GSS source code. Must contain at
#     least one file if compiling GSS (default: gss).
# - java: The Java executable (default: java).
# - js-out: Output path for JS (default: $name.min.js).
# - js-roots: Directories containing JS source code. JS build will
#     *always* include Closure Library goog and third-party roots.
#     (default:)
# - js-warnings: Compiler passes that should be enabled as warnings.
#     (default:).
# - name: The project name. This is used for some other inferred names,
#     and only needs to be present if these derived options are not
#     overridden (default:).
# - namespace: The root JS namespace (default: $name.main).
# - python: The Python executable (default: python).
# - soy-root: The root of Soy source code for templates (default: soy).
# ======================================================================

# Script source (for self updating).
script_source=https://raw.github.com/oinksoft/goog.bash/master/goog

# Mirrors for pre-built Closure Tools packages.
: ${GOOG_MIRROR_URL:=http://localhost:8000}

# Directory where goog writes all of its files.
base_dir="$HOME/.goog"

# Possible locations of configuration files.
config_filename=goog.json
config=(
    "$PWD/$config_filename"
    "$HOME/.$config_filename"
    "/etc/$config_filename"
)
loaded_config=

# Where goog downloads packages.
cache="$base_dir/cache"

logfile=goog.log

usage() {
    echo "goog: Google Closure Tools assets manager and build tool."
    echo
    echo "usage: goog <command> [options ...]"
    echo
    echo "Commands:"
    echo "  build        Build project assets."
    echo "  clean        Clean previously built assets."
    echo "  help         Display help about a command."
    echo "  install      Install the Closure Tools locally."
    echo "  mirror       Set up a mirror."
    echo "  self-test    Run this script's tests. Takes a while!"
    echo "  self-update  Replace this script with the latest release from"
    echo "               github."
    echo "  skel         Generate a project skeleton."
    echo
    echo "Configuration files are read in this order:"
    for f in "${config[@]}"
    do
        echo "  $f"
    done
    echo
    echo 'Configuration options:'
    echo '  css-out: Output path for GSS (default: "$name.min.css").'
    echo '  gss-root: Directory containing GSS source code. Must contain at'
    echo '      least one file if compiling GSS (default: "gss").'
    echo '  java: The Java executable (default: "java").'
    echo '  js-out: Output path for JS (default: "$name.min.js").'
    echo '  js-roots: Directories containing JS source code. JS build will'
    echo '      *always* include Closure Library goog and third-party roots.'
    echo '      (default: [])'
    echo '  js-warnings: Compiler passes that should be enabled as warnings.'
    echo '      (default: []).'
    echo '  name: The project name. This is used for some other inferred names,'
    echo '      and only needs to be present if these derived options are not'
    echo '      overridden (default: "").'
    echo '  namespace: The root JS namespace (default: "$name.main").'
    echo '  python: The Python executable (default: "python").'
    echo '  soy-root: The root of Soy source code for templates (default: "soy").'
    exit 1
}

main() {
    case $1 in
        'build')        do_build "$@"       ;;
        'clean')        do_clean "$@"       ;;
        'help')         do_help "$@"        ;;
        'install')      do_install "$@"     ;;
        'mirror')       do_mirror "$@"      ;;
        'self-test')    do_self_test "$@"   ;;
        'self-update')  do_self_update "$@" ;;
        'skel')         do_skel "$@"        ;;
        *)              usage               ;;
    esac
}

# ======================================================================
# Configuration loading and access
# ======================================================================

load_config() {
    for f in "${config[@]}" ; do
        if [[ -r "$f" ]] ; then
            loaded_config="$loaded_config$(parse_config "$f")\n"
        fi
    done
}

parse_config() {
    if ! grep -v '^[[:space:]]*//' "$1" | json_tokenize | json_parse ; then
        echo "error: Could not parse config file $1"
        exit 1
    fi
}

config() {
    local v="$(json_get "$1" "$loaded_config")"
    if [[ -n "$v" ]] ; then
        echo "$v"
    else
        echo "$2"
    fi
}

# ======================================================================
# build [<all|js|templates|gss|>]
# ======================================================================

do_build() {
    if [[ ! -e "$base_dir" ]] ; then
        echo "error: Missing base dir at $base_dir."
        echo '       Perhaps you should run `goog install`'
        exit 1
    else
        load_config
        local name="$(config name)"
        local target
        if [[ -n "$2" ]] ; then
            target="$2"
        else
            target=all
        fi
        case "$target" in
            all)       build_gss && build_templates && build_js ;;
            gss)       build_gss       ;;
            js)        build_js        ;;
            templates) build_templates ;;
            *)         build_usage ; exit 1 ;;
        esac
    fi
}

build_gss() {
    report "Building GSS"
    local name="$(config name)"
    local root="$(config gss-root)"
    local out="$(config css-out "$name.min.css")"
    "$(config java java)" -jar "$base_dir/$install_stylesheets" \
        "$(config gss-root gss)"/* > "$out.tmp"
    mv "$out.tmp" "$out"
    du -h "$out"
    report_sep
}

build_js() {
    report "Building JavaScript"
    local name="$(config name)"
    local namespace="$(config namespace "$name.main")"
    local root_conf="$(config js-roots js)"
    local out="$(config js-out "$name.min.js")"
    local tmp="$out.tmp"
    local warning_conf="$(config js-warnings)"
    local roots=
    local warnings=
    for w in $warning_conf ; do
        warnings="$warnings -f --jscomp_warning=$w "
    done
    for r in $root_conf ; do
        roots="--root=$r "
    done
    log_now build-js
    rm -f "$tmp"
    "$(config python python)" \
        "$base_dir/$install_lib/closure/bin/build/closurebuilder.py" \
        --root="$base_dir/$install_lib/closure/goog" \
        --root="$base_dir/$install_lib/third_party/closure/goog" \
        $roots \
        --namespace="$namespace" \
        --output_mode=compiled \
        --compiler_jar="$base_dir/$install_compiler" \
        $warnings \
        -f --js="$base_dir/$install_lib/closure/goog/deps.js" \
        -f --generate_exports \
        -f --output_wrapper=';(function(){%output%})();' \
        -f --compilation_level=ADVANCED_OPTIMIZATIONS \
        --output_file="$tmp" 2>&1 \
        | tee -a "$logfile" \
        | grep -v closurebuilder.py
    if (( ! ${PIPESTATUS[0]} )) ; then
        mv -f "$tmp" "$out"
        du -h "$out"
    fi
    report_sep
}

build_templates() {
    report "Building Templates"
    report_sep
}

build_usage() {
    echo "build: Build project assets."
    echo
    echo "usage: goog build [<all|js|templates|gss>]"
    echo
    echo "  target  The assets to build (default: all)"
}

# ======================================================================
# clean
# ======================================================================

do_clean() {
    load_config
    report Cleaning
    local gss_out="$(config gss-out)"
    # TODO: Clean template JS files and CSS map file.
    local js_out="$(config js-out)"
    rm -f "$gss_out" "$js_out" "$logfile"
    echo done
}

clean_usage() {
    echo "clean: Clean previously built assets."
    echo
    echo "usage: goog clean"
}

# ======================================================================
# help <command>
# ======================================================================

do_help() {
    case "$2" in
        'build')       build_usage        ;;
        'clean')       clean_usage        ;;
        'help')        help_usage         ;;
        'install')     install_usage      ;;
        'mirror')      mirror_usage       ;;
        'self-test')   self_test_usage    ;;
        'self-update') self_update_usage  ;;
        'skel')        skel_usage         ;;
        *)             usage              ;;
    esac
    exit 1
}

help_usage() {
    echo "help: Get help"
    echo
    echo "usage: goog help <command>"
    echo
    echo "  command  Usage is shown for the requested command"
}

# ======================================================================
# install
# ======================================================================

install_lib=library
install_compiler='compiler.jar'
install_templates='soy.jar'
install_stylesheets='closure-stylesheets.jar'
install_targets=(
    "$install_lib"
    "$install_compiler"
    "$install_templates"
    "$install_stylesheets"
)

do_install() {
    echo Installing Google Closure Tools ...
    echo "  Base dir: $base_dir"
    mkdir -p "$cache"
    clean_install "$install_targets"
    backup_install "$install_targets"
    report_sep
    install_library
    install_compiler
    install_templates
    install_stylesheets
    echo done
}

install_usage() {
    echo "install: Install the Closure Tools to the home directory."
    echo
    echo "usage: goog install"
}

clean_install() {
    cd "$base_dir"
    for t in "${install_targets[@]}" ; do
        rm -rf "$t.orig"
    done
}

backup_install() {
    cd "$base_dir"
    for t in "${install_targets[@]}" ; do
        if [[ -e "$t" ]] ; then
            mv -f "$t" "$t.orig"
        fi
    done
}

lib_archive="$install_lib.tar.gz"

install_library() {
    cd "$cache"
    report 'Closure Library: Downloading'
    rm -f "$lib_archive"
    if download "$GOOG_MIRROR_URL/$lib_archive" . ; then
        report 'Closure Library: Extracting'
        tar zxf "$lib_archive"
        mv "$install_lib" "$base_dir"
    else
        report 'error: could not download Library'
    fi
    report_sep
}

install_compiler() {
    cd "$cache"
    report 'Closure Compiler: Downloading'
    if ! download "$GOOG_MIRROR_URL/$install_compiler" "$base_dir" ; then
        report 'error: could not download Compiler'
    fi
    report_sep
}

install_templates() {
    cd "$cache"
    report 'Closure Templates: Downloading'
    if ! download "$GOOG_MIRROR_URL/$install_templates" "$base_dir" ; then
        report 'error: could not download Compiler'
    fi
    report_sep
}

install_stylesheets() {
    cd "$cache"
    report 'Closure Stylesheets: Downloading'
    if ! download "$GOOG_MIRROR_URL/$install_stylesheets" "$base_dir" ; then
        report 'error: could not download Compiler'
    fi
    report_sep
}

# ======================================================================
# mirror <build_path> <out_path>
# ======================================================================

do_mirror() {
    if (( $# < 3 )) ; then
        mirror_usage
    else
        local build_path="$(realpath "$(dirname "$2")")/$(basename "$2")"
        local out_path="$(realpath "$(dirname "$3")")/$(basename "$3")"
        if mkdir -p "$build_path" "$out_path" ; then
            echo "Installing mirror ..."
            echo "  Build root: $build_path"
            echo "  Host root: $out_path"
            report_sep
            if (( $# > 3 )) ; then
                local target="mirror_$4"
                if has_cmd "${target}" ; then
                    "${target}" "${build_path}" "${out_path}"
                else
                    report "error: target "${4}" does not exist"
                fi
            else
                mirror_library "$build_path" "$out_path"
                mirror_compiler "$build_path" "$out_path"
                mirror_templates "$build_path" "$out_path"
                mirror_stylesheets "$build_path" "$out_path"
            fi
            echo done
        fi
    fi
}

mirror_usage() {
    echo 'mirror: Set up a mirror for the `install'"' command."
    echo
    echo "usage: goog mirror <build_path> <out_path> [<target>]"
    echo
    echo "  build_path  The directory where packages are built. It will be"
    echo "              created if it does not already exist"
    echo "  out_path    The directory where publicly mirrored files are"
    echo "              hosted. It will be created if it does not already"
    echo "              exist."
    echo "  target      A build target ('compiler', 'templates', 'stylesheets',"
    echo "              'library')"
    echo
    echo "Requires ant, git, and a JDK"
}

# Mirror targets
mirror_lib=library
mirror_compiler=compiler
mirror_templates=templates
mirror_stylesheets=stylesheets

# Mirror build targets
mirror_lib_archive="$mirror_lib.tar.gz"
mirror_compiler_jar='compiler.jar'
mirror_templates_jar='soy.jar'
mirror_stylesheet_jar='closure-stylesheets.jar'

# Mirror source URLs
mirror_lib_url='https://code.google.com/p/closure-library/'
mirror_compiler_url='https://code.google.com/p/closure-compiler/'
mirror_templates_url='https://github.com/oinksoft/closure-templates.git'
mirror_stylesheet_url='https://code.google.com/p/closure-stylesheets/'

mirror_header() {
    report "Mirroring $1"
}

mirror_downloading() {
    report "Downloading $1"
}

mirror_updating() {
    report "Updating $1"
}

mirror_archiving() {
    report "Building archive at $1"
}

mirror_building() {
    report "Building $1"
}

mirror_footer() {
    report "Target installed at $1"
    report_sep
}

mirror_library() {
    local name='Closure Library'
    mirror_header "$name"
    cd "$1"
    if [[ ! -e "$mirror_lib" ]] ; then
        mirror_downloading "$name"
        git clone -q "$mirror_lib_url" "$mirror_lib"
        cd "$mirror_lib"
    else
        cd "$mirror_lib"
        mirror_updating "$name"
        git pull -q
    fi
    mirror_archiving "$mirror_lib_archive"
    git archive -o "$mirror_lib.tar" --prefix="$mirror_lib/" HEAD
    gzip -f "$mirror_lib.tar"
    mv "$mirror_lib_archive" "$2"
    mirror_footer "$mirror_lib_archive"
}

mirror_compiler() {
    local name='Closure Compiler'
    mirror_header "$name"
    if ! has_cmd ant ; then
        report 'error: ant required to build the Compiler'
        return 1
    fi
    cd "$1"
    local name
    if [[ ! -e "$mirror_compiler" ]] ; then
        mirror_downloading "$name"
        git clone -q "$mirror_compiler_url" "$mirror_compiler"
        cd "$mirror_compiler"
    else
        cd "$mirror_compiler"
        mirror_updating "$name"
        git pull -q
    fi
    mirror_building "$mirror_compiler_jar"
    log_now build-compiler
    ant jar >> "$logfile" 2>&1
    mv "build/$mirror_compiler_jar" "$2"
    mirror_footer "$mirror_compiler_jar"
}

mirror_templates() {
    local name='Closure Templates'
    mirror_header "$name"
    if ! has_cmd ant ; then
        report 'error: ant required to build the Templates'
        return 1
    fi
    cd "$1"
    if [[ ! -e "$mirror_templates" ]] ; then
        mirror_downloading "$name"
        git clone -q "$mirror_templates_url" "$mirror_templates"
        cd "$mirror_templates"
    else
        cd "$mirror_templates"
        mirror_updating "$name"
        git pull -q
    fi
    mirror_building "$mirror_templates_jar"
    log_now build-templates
    ant -q jar >> "$logfile" 2>&1
    mv "build/$mirror_templates_jar" "$2"
    mirror_footer "$mirror_templates_jar"
}

mirror_stylesheets() {
    local name='Closure Stylesheets'
    mirror_header "$name"
    if ! has_cmd ant ; then
        report 'error: ant required to build the Stylesheets'
        return 1
    fi
    cd "$1"
    if [[ ! -e "$mirror_stylesheets" ]] ; then
        mirror_downloading "$name"
        git clone -q "$mirror_stylesheet_url" "$mirror_stylesheets"
        cd "$mirror_stylesheets"
    else
        cd "$mirror_stylesheets"
        mirror_updating "$name"
        git pull -q
    fi
    mirror_building "$mirror_stylesheet_jar"
    log_now build-stylesheets
    ant jar >> "$logfile" 2>&1
    mv "build/$mirror_stylesheet_jar" "$2"
    mirror_footer "$mirror_stylesheet_jar"
}

# ======================================================================
# self-update
# ======================================================================

do_self_update() {
    local dir="$(dirname "$0")"
    local tmp="$0.tmp"
    if [[ ! -w "$0" ]] ; then
        report "error: goog script path \`$0' not writable."
        exit 1
    else
        if [[ -e "$0" && ! -w "$0" ]] ; then
            report "error: goog script \`$0' not writable."
            exit 1
        else
            echo -n "Updating \`$0' ... "
            mv "$0" "$tmp" \
                && download "$script_source" "$dir" \
                    --no-check-certificate \
                && rm "$tmp" \
                && chmod a+x "$0"
            echo done
        fi
    fi
}

self_update_usage() {
    echo 'self-update: Replace this script with the latest release from github.'
    echo
    echo 'usage: goog self-update'
}

# ======================================================================
# skel <path>
# ======================================================================

skel_default='closure-project'

do_skel() {
    if [[ $# -lt 2 ]] ; then
        local skel="$skel_default"
    else
        local skel="$2"
    fi
    local base="$(skel_namespace "$skel")"
    echo -n "Creating new project at $skel/ ... "
    mkdir -p "$skel"
    skel_sources "$base" "$skel"
    skel_config "$base" > "$skel/$config_filename"
    skel_makefile "$base" > "$skel/Makefile"
    echo done
}

skel_usage() {
    echo "skel: Generate a project skeleton."
    echo
    echo "usage: goog skel <path>"
    echo
    echo "  path  The directory where the new project will be created."
    echo "        This directory will be created if it does not already exist."
}

skel_namespace() {
    echo "$1" | tr '[A-Z]' '[a-z]' | sed -e 's/[^A-Za-z0-9]//g'
}

skel_sources() {
    mkdir -p "$2"/{js,soy,gss}
    skel_js "$1" > "$2/js/main.js"
    skel_gss "$1" > "$2/gss/01-global.gss"
    skel_tpl "$1" > "$2/soy/tpl.soy"
}

skel_config() {
    cat <<EOF
// goog.bash config file generated at $(date)

{
  "name": "$1",
  "namespace": "$1.main",
  "js-roots": ["js"],
  "js-out": "$1.min.js",
  "gss-root": "gss",
  "css-out": "$1.min.css",
  "soy-root": "soy"
}
EOF
}

skel_makefile() {
    cat <<EOF
# Makefile generated at $(date)

GOOG ?= goog

all: $1

$1:
	\$(GOOG) build

clean:
	\$(GOOG) clean

.PHONY: all $1 clean
EOF
}

skel_js() {
    echo "goog.provide('$1.main')"
    echo
    echo "$1.main = function() {};"
}

skel_gss() {
    echo 'body { background: white; }'
}

skel_tpl() {
    echo '{namespace $1.tpl}'
    echo
    echo '/**'
    echo ' */'
    echo '{template .main}'
    echo '{/template}'
}

# ======================================================================
# Utilities
# ======================================================================

download() {
    if has_cmd wget ; then
        wget -q -P "$2" "$1"
    else
        curl -s "$1" > "$2/$(basename $1)"
    fi
}

log_now() {
    echo "-- $1 -- $(date) --" >> "$logfile"
}

has_cmd() { hash "$1" &>/dev/null ; }
report() { echo "* $1" ; }
report_sep() { echo ---------------------------------------- ; }
inc() { eval "$1"="$(eval expr \$$1 + 1)" ; }

json_get() {
    local match="$(json_match "$1" "$2")"
    local val="$(json_match_val "$match")"
    normalize_json "$1" "$val" "$2"
}

json_match() { echo -e "$2" | grep "^\[\"$1\"\]" | head -1 ; }
json_match_val() { echo "$1" | awk '{ print $2 }' ; }
json_string() { echo ${1:1:`expr ${#1} - 2`} ; }
is_json_string() { echo "$1" | grep -q '^"' ; }

# Normalize JSON -- only one level deep (no nested arrays or objects) --
# into bash terms.
normalize_json() {
    # Value is Array
    if echo "$2" | grep -q '^\[' ; then
        local i=0
        local patt
        local match
        local val
        while : ; do
            patt="^\[\"$1\",$i\]"
            if match="$(echo "$3" | grep "$patt")" ; then
                val="$(json_match_val "$match")"
                if is_json_string "$val" ; then
                    echo -n "$(json_string "$val") "
                else
                    echo -n "$val "
                fi
                inc i
            else
                break
            fi
        done
    else
        if is_json_string "$2" ; then
            echo $(json_string "$2")
        fi
    fi
}

# ======================================================================
# JSON.sh
# URL: <https://github.com/dominictarr/JSON.sh>
# Rev: 955fc917cc7308bf682857a65c10e464b557c51a
#
# Don't edit this unless there's good reason to!
# ======================================================================

# The MIT License
#
# Copyright (c) 2011 Dominic Tarr
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

JSON_BRIEF=0
JSON_LEAFONLY=0
JSON_PRUNE=0

json_tokenize() {
  local ESCAPE='(\\[^u[:cntrl:]]|\\u[0-9a-fA-F]{4})'
  local CHAR='[^[:cntrl:]"\\]'
  local STRING="\"$CHAR*($ESCAPE$CHAR*)*\""
  local NUMBER='-?(0|[1-9][0-9]*)([.][0-9]*)?([eE][+-]?[0-9]*)?'
  local KEYWORD='null|false|true'
  local SPACE='[[:space:]]+'
  {
    egrep -ao "$STRING|$NUMBER|$KEYWORD|$SPACE|." --color=never 2>/dev/null ||
    egrep -ao "$STRING|$NUMBER|$KEYWORD|$SPACE|." # busybox egrep
  } |
     egrep -v "^$SPACE$"  # eat whitespace
}

json_parse_array() {
  local index=0
  local ary=''
  read -r json_token
  case "$json_token" in
    ']') ;;
    *)
      while :
      do
        json_parse_value "$1" "$index" || return 1
        index=$((index+1))
        ary="$ary""$value"
        read -r json_token
        case "$json_token" in
          ']') break ;;
          ',') ary="$ary," ;;
          *) return 1 ;;
        esac
        read -r json_token
      done
      ;;
  esac
  [ "$JSON_BRIEF" -eq 0 ] && value=`printf '[%s]' "$ary"` || value=
  :
}

json_parse_object() {
  local key
  local obj=''
  read -r json_token
  case "$json_token" in
    '}') ;;
    *)
      while :
      do
        case "$json_token" in
          '"'*'"') key=$json_token ;;
          *) return 1 ;;
        esac
        read -r json_token
        case "$json_token" in
          ':') ;;
          *) return 1 ;;
        esac
        read -r json_token
        json_parse_value "$1" "$key" || return 1
        obj="$obj$key:$value"
        read -r json_token
        case "$json_token" in
          '}') break ;;
          ',') obj="$obj," ;;
          *) return 1 ;;
        esac
        read -r json_token
      done
    ;;
  esac
  [ "$JSON_BRIEF" -eq 0 ] && value=`printf '{%s}' "$obj"` || value=
  :
}

json_parse_value() {
  local jpath="${1:+$1,}$2" isleaf=0 isempty=0 print=0
  case "$json_token" in
    '{') json_parse_object "$jpath" || return 1 ;;
    '[') json_parse_array  "$jpath" || return 1 ;;
    # At this point, the only valid single-character tokens are digits.
    ''|[!0-9]) return 1 ;;
    *) value=$json_token
       isleaf=1
       [ "$value" == '""' ] && isempty=1
       ;;
  esac
  [ "$value" == '' ] && return
  [ "$JSON_LEAFONLY" -eq 0 ] && [ "$JSON_PRUNE" -eq 0 ] && print=1
  [ "$JSON_LEAFONLY" -eq 1 ] && [ "$isleaf" -eq 1 ] && [ $JSON_PRUNE -eq 0 ] && print=1
  [ "$JSON_LEAFONLY" -eq 0 ] && [ "$JSON_PRUNE" -eq 1 ] && [ "$isempty" -eq 0 ] && print=1
  [ "$JSON_LEAFONLY" -eq 1 ] && [ "$isleaf" -eq 1 ] && \
    [ $JSON_PRUNE -eq 1 ] && [ $isempty -eq 0 ] && print=1
  [ "$print" -eq 1 ] && printf "[%s]\t%s\n" "$jpath" "$value"
  :
}

json_parse() {
  read -r json_token
  json_parse_value || return 1
  read -r json_token
  case "$json_token" in
    '') ;;
    *) return 1 ;;
  esac
}

# ======================================================================
# End JSON.sh
# ======================================================================

# ======================================================================
# self-test [<suites>]
#
# Warning, some of these will take a while to run.
# ======================================================================

tests_failed=0
tests_passed=0
tests_run=0

report_test() {
    report "$tests_passed of $tests_run tests passed."
}

do_self_test() {
    echo 'Running test suite ...'
    local state="$(test_setup)"
    if [[ $# -gt 1 ]] ; then
        local suites=(${@:2})
    else
        local suites=(
            'install'
            'skel'
        )
    fi
    if [[ -z "$state" ]] ; then
        report "error: Test setup failed"
        exit 1
    else
        report_sep
        for s in "${suites[@]}" ; do
            echo "Running tests: $s ..."
            "test_$s" "$state"
            report_sep
        done
        report_test
        test_teardown "$state"
    fi
}

self_test_usage() {
    echo 'self-test: Run the `goog'"' script's tests."
    echo
    echo "usage: goog self-test"
}

test_setup() {
    if [[ -e "$base_dir" ]] ; then
        rm -rf "$base_dir.orig"
        mv "$base_dir" "$base_dir.orig"
        mkdir -p "$cache"
    fi
    mktemp -d
}

test_install() {
    cd "$1"
    do_mirror _ "$1/build" "$1/host"
    cd host
    nohup python -m SimpleHTTPServer &
    cd ..
    do_install
    for t in "${install_targets[@]}" ; do
        assert exists "$base_dir/$t" "$LINENO"
    done
}

test_skel() {
    do_skel _ "$1"
    assert exists "$1/js/main.js" "$LINENO"
    assert exists "$1/gss/01-global.gss" "$LINENO"
    assert exists "$1/soy/tpl.soy" "$LINENO"
}

test_teardown() {
    rm -rf $1
    if [[ -e "$base_dir.orig" ]] ; then
        mv "$base_dir.orig" "$base_dir"
    fi
}

assert() {
    local fn
    if [[ $# -lt 3 ]] ; then
        fn=true
    else
        fn="$1"
        shift
    fi
    if "assert_$fn" "$1" ; then
        inc tests_passed
        inc tests_run
    else
        inc tests_failed
        inc tests_run
        report "[FAIL] L$2: Assert $fn \"$1\""
    fi
}

assert_true() {
    [[ -n "$1" ]]
}

assert_exists() {
    [[ -e "$1" ]]
}

# Script entry point
main "$@"
