#!/bin/bash

# a wrapper script to run the unit-tests. On the host it shall setup a one node
# vagrant environment and trigger the unit tests in the sandbox vm. This is
# needed since some unit-tests depend on the external daemon like ovs, etcd
# etc to be setup.

USAGE="${0} -vagrant"
PATH=$PATH:/usr/local/go/bin

run_in_vagrant=false
coverage_basic=false
coverage_detail=false
test_packages="github.com/contiv/netplugin/drivers \
    github.com/contiv/netplugin/state \
    github.com/contiv/netplugin/netplugin/plugin \
    github.com/contiv/netplugin/utils/netutils \
    github.com/contiv/netplugin/gstate \
    github.com/contiv/netplugin/netmaster/master \
    github.com/contiv/netplugin/netmaster/mastercfg \
    github.com/contiv/netplugin/netmaster/client \
    github.com/contiv/netplugin/resources \
    github.com/contiv/netplugin/core \
    github.com/contiv/netplugin/utils \
    github.com/contiv/netplugin/mgmtfn/k8splugin/contivk8s \
    "

while [ "${#}" -gt 0 ]
do
    case "${1}" in
        -vagrant)
            run_in_vagrant=true
	    ;;
        -c0|--coverage-basic)
            coverage_basic=true
            ;;
        -c1|--coverage-detail)
            coverage_detail=true
            ;;
        *)
            echo "${USAGE}" 1>&2
            exit 1;;
    esac
    shift
done

# running on host
if ${run_in_vagrant}; then
    (CONTIV_NODE_OS="${CONTIV_NODE_OS}" CONTIV_NODES=1 vagrant up)
    ret=$?
    if [ ${ret} -ne 0 ]; then
        (CONTIV_NODES=1 vagrant destroy -f)
        exit 1
    fi

    # XXX: running unit-tests require root permission due to dependence on ovs
    # utilities. Need to find a way without 'sudo'.
    (CONTIV_NODES=1 vagrant ssh netplugin-node1 -c 'sudo -E PATH=$PATH $GOSRC/github.com/contiv/netplugin/'${0})
    ret=$?
    if [ ${ret} -ne 0 ]; then
        if [ -f /var/log/contivk8s.log ]; then
	    cat /var/log/contivk8s.log
        fi

        (CONTIV_NODES=1 vagrant destroy -f)
        exit 1
    fi

    (CONTIV_NODES=1 vagrant destroy -f)
    echo "Host: Tests succeeded!"
    exit 0
fi

for pkg in ${test_packages}
do
  # running in the sand box
  if ${coverage_basic}; then
      (cd $GOSRC/github.com/contiv/netplugin && \
      $GOBIN/godep go test ${pkg} -coverprofile=cover.out) || exit 1
  elif ${coverage_detail}; then
      (cd $GOSRC/github.com/contiv/netplugin && \
      $GOBIN/godep go test ${pkg} -coverprofile=cover.out && \
      $GOBIN/godep go tool cover -func=cover.out) || exit 1
  else
      (cd $GOSRC/github.com/contiv/netplugin && \
      $GOBIN/godep go test -v ${pkg}) || exit 1
  fi
done

echo "Sandbox: Tests succeeded!"
exit 0
