#!/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
DOCKER_REGISTRY=${DOCKER_REGISTRY:-'127.0.0.1:5042'}
USER_PARAMS=${USER_PARAMS:-null}
SOLUM_PARAMS=${SOLUM_PARAMS:-null}
USE_DRONE=${_SYSTEM_USE_DRONE:-null}
GIT_PRIVATE_KEY=${REPO_DEPLOY_KEYS:-''}

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

function TLOG () {
  TLOG_FILTERED $*
}

LOG_FILE=$(GET_LOGFILE)

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

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

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

# Make sure the chef LP exists; build if it doesn't.
docker inspect solum/chef || docker build -t solum/chef $HERE/../../../examples/language-packs/chef/

GIT=$1
shift
COMMIT_SHA=$1
shift
TENANT=$1
shift

ENTRYPOINT="$@"
shift

TLOG "Executing test command $ENTRYPOINT"

BASE_DIR=/dev/shm
DIR_NAME=$(mktemp -u XXXXXXXXXXXXXXXXXXXXXXX | tr '[:upper:]' '[:lower:]' | head -n 1)

APP_DIR=$BASE_DIR/solum/$DIR_NAME
rm -rf $APP_DIR
PRUN mkdir -p $APP_DIR

add_ssh_creds "$GIT_PRIVATE_KEY" "$APP_DIR"

if ! (test_public_repo $GIT); then
    TLOG Could not reach $GIT with curl. Failing.
    exit 1
fi

if [[ $COMMIT_SHA ]]; then
  git_clone_with_retry $GIT $APP_DIR/code
  cd $APP_DIR/code
  PRUN git checkout -B solum_testing $COMMIT_SHA
else
  git_clone_with_retry $GIT $APP_DIR/code --single-branch
  cd $APP_DIR/code
fi

DRONE_ENTRYPOINT=$ENTRYPOINT
DOCKER_ENTRYPOINT=$ENTRYPOINT

# copy params to the working dir
EXT=$(mktemp -u XXX | head -n 1)
if [[ $USER_PARAMS != null ]]; then
  cp $USER_PARAMS $APP_DIR/code/user_params.$EXT
  DRONE_ENTRYPOINT="/bin/bash -c 'source user_params.$EXT && $ENTRYPOINT'"
  DOCKER_ENTRYPOINT="[\"/bin/bash\", \"-c\", \"source user_params.$EXT && $ENTRYPOINT\"]"
fi
if [[ $SOLUM_PARAMS != null ]]; then
  cp $SOLUM_PARAMS $APP_DIR/code/solum_params.$EXT
fi

COMMIT_ID=$(git log -1 --pretty=%H)
echo "$GIT_PRIVATE_KEY" > $APP_DIR/code/id_rsa
# Test the application code
TLOG "===>" Testing App

if [[ $USE_DRONE != null && $(type drone) ]]; then
  TLOG "===>" Using Drone
  if [[ ! -e $APP_DIR/code/.drone.yml ]]; then
    TLOG "===>" Creating .drone.yml
    cat << EOF > $APP_DIR/code/.drone.yml
image: solum/chef
script:
- $DRONE_ENTRYPOINT
EOF
  else
    TLOG "===>" .drone.yml found in source
  fi
  sudo /usr/local/bin/drone build $APP_DIR/code 2>&1 > >(while read LINE; do TLOG $LINE; done)
else
  TLOG Creating Dockerfile
  cat << EOF > $APP_DIR/Dockerfile
# SOLUM APP BUILDER
FROM solum/chef
ADD code /code
ADD code/id_rsa /root/.ssh/id_rsa
RUN chmod 0600 /root/.ssh/id_rsa
RUN echo "Host *\n\tStrictHostKeyChecking no\n\tUserKnownHostsFile=/dev/null" > /root/.ssh/config
WORKDIR /code
RUN ${DOCKER_ENTRYPOINT}
EOF

  cd $APP_DIR
  sudo docker build --rm -t $DIR_NAME . 2>&1 > >(while read LINE; do TLOG $LINE; done)
fi

SUCCESS=$?
remove_ssh_creds "$GIT_PRIVATE_KEY"
echo Docker finished with status $SUCCESS.

if [[ $SUCCESS == 0 ]]; then
TLOG ==== Status: SUCCESS
else
TLOG ==== Status: FAIL
fi

[[ $SUCCESS == 0 ]] && sudo docker rmi $DIR_NAME
cd /tmp
rm -rf $APP_DIR

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
