#!/usr/bin/env bash

set -e -x

# Docker Cloud doesnt set USER
export USER=${USER:-root}

# Run tests
docker run -i --volume="$(pwd)/tests:/work" "$IMAGE_NAME" /bin/sh -c "
  set -e -x;
  /work/pytest.sh;
  /work/vcs.sh;
  /work/opensuse.sh;
"

# Verify MarkdownBear works outside of coala-bears directory.
# See https://github.com/coala/coala-bears/issues/1235
docker run -i "$IMAGE_NAME" /bin/sh -c "
  set -e -x;
  cd /tmp;
  echo foo > foo.md;
  coala --non-interactive --no-config --bears MarkdownBear --files foo.md;
"

# Verify that image fails in neither a command or work directory are given.
! docker run "$IMAGE_NAME"

# Verify that a missing .coafile in the work directory causes coala-quickstart
# to be run, creating a .coafile that is visible outside of the container.
docker run --volume="$(pwd)/.ci/sample:/work" --workdir=/work "$IMAGE_NAME"
ls -la ./.ci/sample/.coafile

# Verify a .coafile present causes coala-ci to run, with a custom bears loaded,
# and a non-zero exit status occurs when a bear emits a result.
sudo chown "$USER" ./.ci/sample/.coafile
echo -e "[fail]\nbears = NoCommentsBear\nfile = **.py" >> ./.ci/sample/.coafile
! docker run --volume="$(pwd)/.ci/sample:/work" \
             --volume="$(pwd)/.ci/bears:/additional_bears" \
             --workdir=/work "$IMAGE_NAME"

# Run coala
# https://github.com/coala/coala-bears/issues/1037
if [[ "$TRAVIS" == "true" && "$TRAVIS_PULL_REQUEST" != "false" ]]; then
  sed -i.bak '/bears = GitCommitBear/d' .coafile
fi

docker run --volume="$(pwd):/work" --workdir=/work "$IMAGE_NAME"
