#!/bin/sh
#
########################################################################
# Integration Build Script
#  $1 = all (Run integration tests)
#
#  Maintainer: id774 <idnanashi@gmail.com>
#
#  v1.5 6/28,2013
#       Always using latest gems.
#  v1.4 5/13,2013
#       Fix bundler environment.
#  v1.3 2/26,2013
#       Remove script/bootstrap.
#  v1.2 6/16,2012
#       Add all option for integration tests.
#  v1.1 6/14,2012
#       Correspond to unscaffold subcommand.
#  v1.0 3/16,2012
#       First.
########################################################################

kickstart() {
    export RACK_ROOT="."
    export RACK_ENV="test"
    #export DATABASE_URL="$RACK_ROOT/db"
    ruby -v
    test_subcommand log info started.
}

exec_rspec() {
    $RACK_ROOT/bin/automatic -v
    #bundle install --path vendor/gems
    bundle update
    bundle exec rake simplecov
}

run_test() {
    while [ $# -gt 0 ]
    do
        bundle exec $RACK_ROOT/bin/automatic -c $1
        test_subcommand log info $?
        shift
    done
}

load_tests() {
    for YAML_FILE in "$RACK_ROOT/test/integration/test_*.yml"
    do
        run_test $YAML_FILE
    done
    unset YAML_FILE
}

test_subcommand() {
    $RACK_ROOT/bin/automatic $*
}

test_scaffold() {
    test_subcommand scaffold
    test_subcommand unscaffold
}

added_tests() {
    test -f $HOME/.automatic || test_scaffold
    test_subcommand autodiscovery http://blog.id774.net/blogs/
    test_subcommand opmlparser "$RACK_ROOT/test/fixtures/sampleOPML.xml"
    test_subcommand feedparser http://blog.id774.net/blogs/feed/ > /dev/null
    test_subcommand log info finished.
}

integration() {
    load_tests
    added_tests
}

main() {
    kickstart
    exec_rspec
    test -n "$1" && integration
}

set -ex
main $*
