#!/bin/bash
# Copyright 2014 - Rackspace Hosting
#
#    Licensed under the Apache License, Version 2.0 (the "License");
#    you may not use this file except in compliance with the License.
#    You may obtain a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS,
#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#    See the License for the specific language governing permissions and
#    limitations under the License.


# Solum App Unit Test Script for Docker

SCRIPT_START_TIME=$(date +"%s")

PROJECT_ID=${PROJECT_ID:-null}
BUILD_ID=${BUILD_ID:-null}
TASKNAME=unittest

# TLOG, PRUN, ENSURE_LOGFILE, and elapsed defined in app-common
HERE=$(dirname $0)
source $HERE/app-common

LOG_FILE=$(GET_LOGFILE)

TLOG ===== Starting Test Script $0 $*

# Make sure tenant auth credentials were passed in
if [[ -z $OS_AUTH_TOKEN ]]; then
  TLOG openstack credentials not passed via ENV.
  exit 1
fi

# Check command line arguments
if [ $# -lt 4 ]; then
  TLOG Usage: $0 git_url git_branch tenant unit_test_entry_point
  exit 1
fi

PRUN silent docker ps
[[ $? != 0 ]] && TLOG Cannot talk to docker. && exit 1

GIT=$1
shift
GIT_BRANCH=$1
shift
TENANT=$1
shift

ENTRYPOINT="$@"
shift

TLOG "Executing test command $ENTRYPOINT"
DOCKER_REGISTRY=${DOCKER_REGISTRY:-'127.0.0.1:5042'}

# Test the application code
TLOG "===>" Testing App

sudo docker run --rm -e GIT_URL=$GIT -e TEST_CMD="$ENTRYPOINT" $DOCKER_REGISTRY/slugtester 2>&1 > >(while read LINE; do TLOG $LINE; done)

SUCCESS=$?
TLOG Docker finished with status $SUCCESS.

TOTAL_TIME=$(elapsed $SCRIPT_START_TIME)
TLOG ===== Total elapsed time: $TOTAL_TIME sec

# Return 0 if the tests went well, or 1 otherwise.
[[ $SUCCESS = 0 ]] && exit 0 || exit 1
