#!/usr/bin/env bash

set -e -o pipefail

bin=$(cd $(dirname ${BASH_SOURCE[0]}) && pwd)
base=$( cd ${bin}/.. && pwd )
ENV_LOCAL=${bin}/env.windows.local
ENV_LOCAL_TEMPLATE=${bin}/env.windows.template

if [ ! -d $base/tmp ]; then
  mkdir -p $base/tmp
fi

cleanup() {
  echo "Cleaning up"
  pkill -f "vagrant up" || true

  if [ "${SKIP_CLEANUP-false}" != "true" ]; then
    (cd integration/windows && vagrant destroy -f)
  else
    echo "SKIP_CLEANUP set to true, not destroying vagrant instances"
  fi

  if [ -f "$tmpfile" ]; then
    rm -rf $tmpfile
  fi
}

trap cleanup EXIT

cd $base
if [ -f ${ENV_LOCAL} ]; then
    echo -e "\n ${ENV_LOCAL} detected. Sourcing contents"
    source ${ENV_LOCAL}
else
    echo -e "\n Running integration test with existing env. Edit ${ENV_LOCAL_TEMPLATE} to run integration tests locally."
fi

tmpfile=`mktemp -t bosh-agent-tests-XXXXXXXX`
echo "${AWS_SSH_KEY}" > $tmpfile
chmod 600 $tmpfile
export PRIVATE_KEY_PATH=$tmpfile

echo -e "\n Running agent integration tests..."
$bin/env go clean -r github.com/cloudfoundry/bosh-agent/

echo -e "\n Running tests..."
focus=""
if [ ! -z "$BOSH_AGENT_INTEGRATION_FOCUS" ]; then
  focus="-focus=$BOSH_AGENT_INTEGRATION_FOCUS"
fi
bin/env go run github.com/onsi/ginkgo/ginkgo "$focus" -v -race -trace integration/windows/

exit 0
