#!/bin/bash

set -e

REPORT_DIRECTORY='reports/'

diag() {
  echo "$@" 2>&1
}

if ls /var/lib/systemd/coredump/core.perl-fcgi* >/dev/null 2>&1 ; then
  diag "================== NOTE: CORE DUMP DETECTED =================="
  diag "= Removing known cores to prevent failing for the known issues:"
  diag "= 1) MT#21791: Renaming ngcp-panel cores /var/lib/systemd/coredump/core.perl-fcgi*"
  ls -la /var/lib/systemd/coredump/core.perl-fcgi*
  for file in /var/lib/systemd/coredump/core.perl-fcgi* ; do
    mv "${file}" /var/lib/systemd/coredump/RENAMED_"$(basename "${file}")"
  done
  diag "= New cores names are:"
  ls -la /var/lib/systemd/coredump/RENAMED_core.perl-fcgi*
  diag "========================== DONE =============================="
fi

goss="goss-0.3.5-e6140f90+patch_319-linux-amd64"

if [ ! -x "/usr/sbin/${goss}" ] ; then
  diag "Downloading goss and installing as /usr/sbin/${goss}"
  curl -L "https://deb.sipwise.com/files/${goss}" > "/usr/sbin/${goss}"
  chmod +x "/usr/sbin/${goss}"
fi

rm -f /usr/sbin/goss
ln -s "/usr/sbin/${goss}" /usr/sbin/goss

host_yml_file="/etc/ngcp-config/config.$(hostname).yml"
if [ -n "${SKIP_DNS_CHECK_TEST}" ] || [ -n "${SKIP_STRICT_HOSTNAME_TEST}" ] ; then
  diag "Configuring host specific YML config: ${host_yml_file}"
  cat > "${host_yml_file}" << EOF
---
sipwise:
  system_tester:
    skip_dns_check_test: '${SKIP_DNS_CHECK_TEST:-false}'
    skip_strict_hostname_test: '${SKIP_STRICT_HOSTNAME_TEST:-false}'
EOF
else
  # remove the file if exist from the previous run
  rm -f "${host_yml_file}"
fi

diag "Rebuilding test configs in /etc/ngcp-test/"
ngcpcfg build /etc/ngcp-test/* 2>&1
rm -f "${host_yml_file}"

rm -rf "${REPORT_DIRECTORY}"
mkdir -p "${REPORT_DIRECTORY}"
TAP_RESULTS="${REPORT_DIRECTORY}/goss_results.tap"

DEBIAN_RELEASE=$(sed -e 's/\([0-9]*\)\..*/\1/' /etc/debian_version)
# translate Debian codenames that don't have a version number (yet) into according numbers
case "${DEBIAN_RELEASE}" in
  buster*)
    DEBIAN_RELEASE=10
    ;;
  bullseye*)
    DEBIAN_RELEASE=11
    ;;
esac
DEBIAN_RELEASE=$DEBIAN_RELEASE goss -g "/etc/ngcp-tests/goss.yaml" validate --format tap | tee "${TAP_RESULTS}"

exit "${PIPESTATUS[0]}"
