#!/usr/bin/env bash
#
# Capture the omnibus install directory as a CI artifact when the job has
# failed, so we can inspect the partial build state after the fact.
#
# This script is intended to be called as the FIRST step of an `after_script`
# on Linux and macOS GitLab CI jobs, before any cleanup that would remove
# `/opt/cinc-workstation`.
#
# Behavior:
#   - No-op unless CI_JOB_STATUS=failed (so successful jobs do not bloat
#     artifacts with the install tree).
#   - Writes a tarball to ${CI_PROJECT_DIR}/data/debug/install-dir-<platform>.tar.zst
#     (falls back to .tar.gz if zstd is unavailable).
#   - Best-effort: never fails the after_script.
#
set -uo pipefail

INSTALL_DIR="${INSTALL_DIR:-/opt/cinc-workstation}"
PROJECT_DIR="${CI_PROJECT_DIR:-$PWD}"
JOB_STATUS="${CI_JOB_STATUS:-unknown}"
PLATFORM_TAG="${PLATFORM_VER:-${CI_JOB_NAME:-unknown}}"
PLATFORM_TAG="${PLATFORM_TAG//[^A-Za-z0-9._-]/_}"

if [[ "${JOB_STATUS}" != "failed" ]]; then
  echo "snapshot-install-dir: job status is '${JOB_STATUS}', skipping snapshot"
  exit 0
fi

if [[ ! -d "${INSTALL_DIR}" ]]; then
  echo "snapshot-install-dir: install dir '${INSTALL_DIR}' does not exist, nothing to capture"
  exit 0
fi

DEBUG_DIR="${PROJECT_DIR}/data/debug"
mkdir -p "${DEBUG_DIR}" || {
  echo "snapshot-install-dir: failed to create ${DEBUG_DIR}, aborting"
  exit 0
}

# Use sudo when available so we can read root-owned omnibus install trees.
SUDO=""
if command -v sudo >/dev/null 2>&1; then
  SUDO="sudo"
fi

ARCHIVE_BASENAME="install-dir-${PLATFORM_TAG}"

if command -v zstd >/dev/null 2>&1; then
  ARCHIVE_PATH="${DEBUG_DIR}/${ARCHIVE_BASENAME}.tar.zst"
  echo "snapshot-install-dir: capturing ${INSTALL_DIR} -> ${ARCHIVE_PATH}"
  ${SUDO} tar --warning=no-file-changed --warning=no-file-removed \
    -I 'zstd -T0 -3' \
    -cf "${ARCHIVE_PATH}" -C "$(dirname "${INSTALL_DIR}")" "$(basename "${INSTALL_DIR}")" \
    || echo "snapshot-install-dir: tar exited non-zero (continuing)"
else
  ARCHIVE_PATH="${DEBUG_DIR}/${ARCHIVE_BASENAME}.tar.gz"
  echo "snapshot-install-dir: capturing ${INSTALL_DIR} -> ${ARCHIVE_PATH}"
  ${SUDO} tar --warning=no-file-changed --warning=no-file-removed \
    -czf "${ARCHIVE_PATH}" -C "$(dirname "${INSTALL_DIR}")" "$(basename "${INSTALL_DIR}")" \
    || echo "snapshot-install-dir: tar exited non-zero (continuing)"
fi

# Make the archive readable by the runner user so artifact upload can read it.
${SUDO} chown -R "$(id -un)":"$(id -gn)" "${DEBUG_DIR}" 2>/dev/null || true

ls -la "${DEBUG_DIR}" || true
exit 0
