#!/bin/bash

set -eu

if which goctest >/dev/null; then
    goctest="goctest"
else
    goctest="go test"
fi

STATIC_GO=""
STATIC_JS=""
UNIT_GO=""
UNIT_JS=""
export PHANTOMJS_BIN=`pwd`/node_modules/.bin/phantomjs

[ "$#" -eq 0 ] && args="--all" || args="$@"

for arg in $args; do
    case "$arg" in
        --all)
            STATIC_GO="yes"
            STATIC_JS="yes"
            UNIT_GO="yes"
            UNIT_JS="yes"
            ;;
        --go)
            STATIC_GO="yes"
            UNIT_GO="yes"
            ;;
        --js)
            STATIC_JS="yes"
            UNIT_JS="yes"
            ;;
        --static)
            STATIC_GO="yes"
            STATIC_JS="yes"
            ;;
        --static-go)
            STATIC_GO="yes"
            ;;
        --static-js)
            STATIC_JS="yes"
            ;;
        --unit)
            UNIT_GO="yes"
            UNIT_JS="yes"
            ;;
        --unit-go)
            UNIT_GO="yes"
            ;;
        --unit-js)
            UNIT_JS="yes"
            ;;
        --skip-npm-install)
            SKIP_NPM_INSTALL="yes"
            ;;
        *)
            echo "Wrong flag ${1}. To run a single suite use --static, --static-go, --static-js, --unit, --unit-go, --unit-js or --all to run all tests."
            exit 1
    esac
done

# Append the coverage profile of a package to the project coverage.
append_go_coverage() {
    local profile="$1"
    if [ -f $profile ]; then
        cat $profile | grep -v "mode: set" >> .coverage-go/coverage.out
        rm $profile
    fi
}

if [ ! -z "$STATIC_GO" ]; then
    # Run go static tests.

    echo Checking formatting
    fmt=$(gofmt -l .)

    if [ -n "$fmt" ]; then
        echo "Formatting wrong in following files"
        echo "$fmt"
        echo "Getting formating diff..."
        fmt_diff=$(gofmt -d .)
        echo "$fmt_diff"
        exit 1
    fi

    # go vet
    echo Running vet
    go vet ./...

    export PATH=$PATH:$GOPATH/bin

    echo Running lint
    lint=$(golint ./...)
    if [ -n "$lint" ]; then
        echo "Lint complains:"
        echo $lint
        exit 1
    fi

fi

if [ ! -z "$STATIC_JS" ]; then
    npm run js:lint
fi

if [ ! -z "$UNIT_GO" ]; then
    echo Building
    go build github.com/snapcore/snapweb/...

    # Prepare the coverage output profile.
    rm -rf .coverage-go
    mkdir .coverage-go
    echo "mode: set" > .coverage-go/coverage.out

    # tests
    echo Running tests from $(pwd)
    for pkg in $(go list ./... | grep -v integration-tests); do
        $goctest -coverprofile=.coverage-go/profile.out $pkg
        append_go_coverage .coverage-go/profile.out
    done
fi

if [ ! -z "$UNIT_JS" ]; then
    rm -rf .coverage-js

    # js unit tests
    echo "Running js unit tests (set JS_TESTER to override)"
    NODE_ENV=test ${JS_TESTER:- ./node_modules/karma/bin/karma start --single-run}

    cat .coverage-js/text-summary.txt

fi

echo "\nAll good, what could possibly go wrong"
