#!/bin/bash
set -ex

sudo setenforce 0

# find dir one level up, should contain mission-portal
COMPUTED_ROOT=$(readlink -e $(dirname "$0")/../)
# NTECH_ROOT should be same, if available use it so user can override
NTECH_ROOT=${NTECH_ROOT:-$COMPUTED_ROOT}

"${NTECH_ROOT}/mission-portal/ci/check-environment.py"

sudo mkdir -p "$NTECH_ROOT"/artifacts
sudo chown $USER:$USER "$NTECH_ROOT"/artifacts

# get build URL by job
PACKAGE_NAME=$(curl -v --silent http://buildcache.cfengine.com/packages/testing-pr/"$JOB"/PACKAGES_HUB_x86_64_linux_redhat_9/ 2>&1 | grep -Po '(?<=href=")[^"]*.rpm')
if [ ! -f "$PACKAGE_NAME" ]; then
  BUILD_URL="http://buildcache.cfengine.com/packages/testing-pr/$JOB/PACKAGES_HUB_x86_64_linux_redhat_9/$PACKAGE_NAME"
  wget --quiet $BUILD_URL
fi
sudo rpm -e cfengine-nova || sudo rpm -e cfengine-nova --noscripts || true
sudo rpm -e cfengine-nova-hub || sudo rpm -e cfengine-nova-hub --noscripts || true
sudo rm -rf /var/cfengine /opt/cfengine /var/log/CFE* || true
sudo rpm -i "$PACKAGE_NAME"
sudo /var/cfengine/bin/cf-agent -B $(hostname -I | awk ' {print $1}')


# now that cfengine is probably installed, run cf-support if there is an error
trap failure ERR

function failure() {
  pwd
  ls -l
  sudo mkdir -p "${NTECH_ROOT}/artifacts"
  sudo chown $USER "${NTECH_ROOT}/artifacts"
  cd "${NTECH_ROOT}/artifacts"
  ( sudo cf-support --yes 2>&1; echo $? > /tmp/status ) > $$.cfsupportlog
  if [ "$(cat /tmp/status)" != "0" ]; then
    cat $$.cfsupportlog
  fi
  rm -f $$.cfsupportlog
}

sudo setfacl -m u:cfapache:rx /home/jenkins/
sudo setfacl -R -m u:cfapache:rwx -m d:u:cfapache:rwx /home/jenkins/workspace

sudo setfacl -m u:cfpostgres:rx /home/jenkins/
sudo setfacl -R -m u:cfpostgres:rwx -m d:u:cfpostgres:rwx /home/jenkins/workspace

cd "$NTECH_ROOT"/mission-portal
sudo -u cfapache /usr/local/bin/composer install
sudo cp -r /var/cfengine/httpd/htdocs/public/tmp ./public
sudo cp -r /var/cfengine/httpd/htdocs/api .git
sudo cp -r /var/cfengine/httpd/htdocs/application/config/appsettings.php ./application/config/

sudo cp -f ./tests/mocks/sendmail /usr/local/bin/mock-sendmail
sudo chmod +x /usr/local/bin/mock-sendmail
sudo sed -i 's|^;sendmail_path =.*|sendmail_path = /usr/local/bin/mock-sendmail|' /var/cfengine/httpd/php/lib/php.ini
# restart cfengine3 services to apply php.ini changes
sudo service cfengine3 restart
sudo systemctl start xvfb
if ! sudo systemctl is-active --quiet xvfb; then
    echo "xvfb is not running."
    exit 1
fi

CF_MAIL_LOG_FILE="/var/log/sendmail.log"
if sudo test ! -f $CF_MAIL_LOG_FILE; then
  sudo touch $CF_MAIL_LOG_FILE
  sudo chmod 777 $CF_MAIL_LOG_FILE
else
  # reset logs
  sudo bash -c ": > $CF_MAIL_LOG_FILE"
fi

sudo systemctl stop cf-execd
sudo systemctl mask cf-execd
sudo systemctl stop cf-hub
sudo systemctl disable cf-hub


# build and run openldap container
# TODO, if there are changes in the openldap setup we need to rebuild the image and kill/re-run the container
if ! sudo podman images | grep openldap; then
  sudo buildah bud -t openldap -f ./docker/openldap/Dockerfile ./docker/openldap
fi
if ! sudo podman ps | grep openldap; then
  if sudo podman ps -a --filter "name=openldap" | grep openldap; then
    sudo podman start openldap
  else
    # --rm automatically removes the container when it exits
    sudo podman run --rm -d -p 389:389 --name openldap openldap
  fi
fi

# let mission portal running on this host access the openldap container as host openldap
if ! grep "127.0.0.1.*openldap*" /etc/hosts; then
  sudo sed -i '/127.0.0.1/s/$/ openldap/' /etc/hosts
fi

cd "$NTECH_ROOT"/mission-portal/tests
sudo -u cfapache /usr/local/bin/composer update
sudo chown -R cfapache:jenkins ../../mission-portal
sudo mkdir -p /opt/cfengine/federation/cfapache/
sudo chown -R cfapache:jenkins /opt/cfengine

"${NTECH_ROOT}/mission-portal/ci/http2check.sh"

result=running
if [ -v UNIT_TESTS ] && [ "$UNIT_TESTS" -eq 1 ]; then
  sudo --preserve-env=GITLAB_BUILD_REPOSITORY_TOKEN -u cfapache php82 ./vendor/phpunit/phpunit/phpunit --log-junit "${NTECH_ROOT}/artifacts/phpunit-report.xml" --coverage-clover=coverage.xml || result=fail
fi

selenium_log="${NTECH_ROOT}/artifacts/selenium.log"
export SELENIUM_LOG="$selenium_log"
if [ -v SELENIUM ] && [ "$SELENIUM" -eq 1 ]; then
  export DISPLAY=:1
  bash "${NTECH_ROOT}/mission-portal/ci/start-geckodriver.sh" "$selenium_log"
  # Give geckodriver time to start
  sleep 5

  sudo COMPOSER_ALLOW_SUPERUSER=1 /usr/local/bin/composer run db-fixtures

  if [ -n "$RUN_IN_PARALLEL" ]; then
    # Run tests in parallel using groups
    PARALLEL_GROUPS=${PARALLEL_GROUPS:-2}

    for i in $(seq 1 $PARALLEL_GROUPS); do
      sudo --preserve-env=GITLAB_BUILD_REPOSITORY_TOKEN,SELENIUM_LOG php82 ./vendor/phpunit/phpunit/phpunit \
        --group "group$i" \
        --log-junit "${NTECH_ROOT}/artifacts/phpunit-selenium-report-group_$i.xml" \
        --configuration phpunit_selenium.xml &
      pids[$i]=$!
    done

    # Wait for all test processes to complete
    for pid in ${pids[*]}; do
      wait $pid || result=fail
    done

    # run audit logs tests when all tests finished to avoid logs appearing from other tests
    sudo --preserve-env=GITLAB_BUILD_REPOSITORY_TOKEN,SELENIUM_LOG php82 ./vendor/phpunit/phpunit/phpunit \
        --log-junit "${NTECH_ROOT}/artifacts/phpunit-selenium-report-group_0.xml" \
        --configuration phpunit_selenium.xml \
        selenium/xAuditLogTest.php || result=fail
  else
    # Run tests sequentially
    sudo --preserve-env=GITLAB_BUILD_REPOSITORY_TOKEN,SELENIUM_LOG php82 ./vendor/phpunit/phpunit/phpunit \
        --log-junit "${NTECH_ROOT}/artifacts/phpunit-selenium-report.xml" \
        --configuration phpunit_selenium.xml || result=fail
  fi      
fi

sudo "${NTECH_ROOT}/mission-portal/ci/selenium-log-to-javascript-errors-junit-report.sh" "$selenium_log" "${NTECH_ROOT}/artifacts/js-errors-report.xml"

if [ "$result" = "fail" ]; then
  ps -efl | grep java
  sudo systemctl status xvfb
  ps -efl | grep firefox
  ps -efl | grep gecko
  ls -l $(which firefox)
  firefox --version
  ls -l $(which geckodriver)
  geckodriver --version
  sudo /var/cfengine/bin/cf-support --yes
  sudo mv cfengine_support*tar.gz "$NTECH_ROOT"/artifacts/
  failure # call cf-support
  exit 1
fi
