#!/usr/bin/env bash
set -ex
# TODO, make everything in here dynamic and not repeat things already done :(

# find the dir one level up from here, home of all the repositories
COMPUTED_ROOT=$(readlink -e $(dirname "$0")/../../)
# NTECH_ROOT should be the same, but if available use it so user can do their own thing.
NTECH_ROOT=${NTECH_ROOT:-$COMPUTED_ROOT}

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

USER=${USER:-$(whoami)}

mkdir -p "${NTECH_ROOT}/artifacts"

# temporary while I figure out github workflow environment variable things
export SELENIUM=1
if [ ! -d /var/cfengine ]; then
  # ci and local buildscripts should place built packages in $NTECH_ROOT/artifacts
  set +e # to catch errors and copy appropriate logs to artifacts directory
  if ! sudo dpkg -i "$NTECH_ROOT"/artifacts/cfengine-nova-hub*deb; then
    tail /var/log/CFEngine-Install.log
    # github artifacts don't allow `:` in filenames which these install logs have, so put them in a tarball
    tar cfz "${NTECH_ROOT}/artifacts/install-logs.tgz" /var/log/CFEngine-Install-*.log
    tail /var/log/postgresql.log
    cp /var/log/postgresql.log "${NTECH_ROOT}/artifacts/"
    tail /var/cfengine/httpd/logs/error_log
    cp -a /var/cfengine/httpd/logs "${NTECH_ROOT}/artifacts/httpd-logs/"
    exit 1
  fi
  set -e # restore error handling
fi

# 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
}

if [ ! -f /var/cfengine/policy_server.dat ]; then
  sudo /var/cfengine/bin/cf-agent -B $(hostname -I | awk ' {print $1}')
fi

cd "$NTECH_ROOT"/mission-portal
sudo mkdir -p vendor
sudo chown -R cfapache vendor
# TODO FIXME, the below takes way too long
sudo chown -R cfapache . # brutal hammer, will take time but may make things "just work"
sudo touch composer.lock
sudo chown cfapache composer.lock
sudo -u cfapache /usr/local/bin/composer install
sudo cp -r /var/cfengine/httpd/htdocs/public/tmp ./public
sudo chown -R cfapache public
sudo cp -r /var/cfengine/httpd/htdocs/api .
sudo chown -R cfapache api
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

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 pkill cf-execd
sudo mv /var/cfengine/bin/cf-execd{,.disabled}
# restart cfengine3 services to apply php.ini changes
sudo /var/cfengine/httpd/bin/apachectl restart
sudo systemctl restart cfengine3
sudo systemctl stop cf-hub

cd tests
sudo mkdir -p vendor
sudo chown cfapache vendor
sudo touch composer.lock
sudo chown cfapache composer.lock
sudo -u cfapache /usr/local/bin/composer update
mkdir -p /opt/cfengine/federation/cfapache/
sudo mkdir -p /tmp/testdownloads
sudo rm -rf /tmp/testdownloads/*
sudo chown cfapache /tmp/testdownloads

# make artifacts directory for cfapache to write logs, screenshots, database dumps to
chown cfapache "${NTECH_ROOT}/artifacts"

# fixup system php.ini so that tests can create phar archives
sed -ri 's/^(\s|;)phar.readonly = On/phar.readonly = Off/' /etc/php/*/cli/php.ini

# add cfapache to sudoers with NOPASSWD: ALL so it can generate sql dumps with sudo -u cfpostgres
echo "cfapache ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/cfapache

# TODO, make an env var that users can provide via PR comment to use --stop-on-failure (short-circuit, stop at first failure)
result=running
sudo --preserve-env=GITLAB_BUILD_REPOSITORY_TOKEN -u cfapache  ./vendor/phpunit/phpunit/phpunit --coverage-clover="${NTECH_ROOT}/artifacts/coverage.xml" --log-junit "${NTECH_ROOT}/artifacts/phpunit-report.xml" --debug --verbose || result=fail

selenium_log="${NTECH_ROOT}/artifacts/selenium.log"
if [ "$result" != "fail" ] && [ -v SELENIUM ] && [ "$SELENIUM" -eq 1 ]; then
  sudo systemctl daemon-reload
  sudo systemctl restart xvfb
  seljar=selenium-server-standalone-3.4.0.jar
  if [ ! -f $seljar ]; then
    sudo wget --quiet http://selenium-release.storage.googleapis.com/3.4/$seljar
  fi
  export DISPLAY=:1
  sudo pkill -9 firefox || true
  sudo pkill -9 geckodriver || true
  sudo pkill -9 java || true # clean up previous run in case of iterative development
  sudo java -jar ./$seljar 2>&1 | sudo tee "$selenium_log" >/dev/null &
  # Give Selenium time to start
  sleep 10
  result=running
# example of running one or more specific test is using --filter argument
# sudo --preserve-env=GITLAB_BUILD_REPOSITORY_TOKEN ./vendor/phpunit/phpunit/phpunit --configuration phpunit_selenium.xml --filter RedirectAfterLoginTest || result=fail

  sudo --preserve-env=GITLAB_BUILD_REPOSITORY_TOKEN ./vendor/phpunit/phpunit/phpunit --log-junit "${NTECH_ROOT}/artifacts/phpunit-selenium-report.xml"  --filter "/^(?!.*testExport)/"  --debug --verbose --configuration phpunit_selenium.xml || result=fail
fi

sudo chmod +x "${NTECH_ROOT}/mission-portal/ci/selenium-log-to-javascript-errors-junit-report.sh"
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
  exit 1
fi
