#!/bin/bash
#
# Author:: Lance Albertson <lance@osuosl.org>
# Copyright:: Copyright 2024-2026, Cinc Project
# License:: Apache License, Version 2.0
#
# 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.

# Test-stage helper for the self-hosted macOS and FreeBSD runners.
#
# Those runners are shared with the build jobs, which depend on the
# operator-installed toolchain at /opt/omnibus-toolchain. To validate
# a freshly-built package without destroying that install, we rename
# it aside before installing the test package, then restore it on
# cleanup — the same rename-aside pattern build-macos.sh/build-freebsd.sh
# use during builds.
#
# Usage:
#   test-toolchain.sh install <package-glob>   # before_script
#   test-toolchain.sh run                      # script
#   test-toolchain.sh cleanup                  # after_script

INSTALL_DIR="/opt/omnibus-toolchain"
ASIDE_DIR="/opt/omnibus-toolchain.test"
PROFILE="test/integration/cinc-tests"

case "$1" in
  install)
    set -e
    PKG="$2"

    # Recover the operator toolchain from a test job that was cancelled
    # before its cleanup could restore it.
    if [ -d "${ASIDE_DIR}" ]; then
      sudo rm -rf "${INSTALL_DIR}"
      sudo mv "${ASIDE_DIR}" "${INSTALL_DIR}"
    fi

    # Rename the operator install aside so installing (and later
    # removing) the test package cannot clobber it.
    if [ -d "${INSTALL_DIR}" ]; then
      sudo mv "${INSTALL_DIR}" "${ASIDE_DIR}"
    fi

    # ${PKG} is an unquoted glob on purpose so the shell resolves the
    # versioned artifact name. macOS ships a .pkg, FreeBSD a .sh.
    case "${PKG}" in
      *.pkg) sudo installer -pkg ${PKG} -target / ;;
      *.sh)  sudo sh ${PKG} ;;
      *) echo "ERROR: unknown package type: ${PKG}" >&2; exit 1 ;;
    esac
    ;;

  run)
    set -e
    sudo "${INSTALL_DIR}/embedded/bin/cinc-auditor" exec "${PROFILE}" \
      --no-distinct-exit --reporter cli junit:junit.xml
    ;;

  cleanup)
    # Runs from after_script: must tolerate any prior-step failure and
    # never error out, so no `set -e` here.
    sudo rm -rf "${INSTALL_DIR}"
    if [ -d "${ASIDE_DIR}" ]; then
      sudo mv "${ASIDE_DIR}" "${INSTALL_DIR}"
    fi
    ;;

  *)
    echo "Usage: $0 {install <package-glob>|run|cleanup}" >&2
    exit 1
    ;;
esac
