#!/usr/bin/env bash
set -euo pipefail
root=/opt/devsecops
mode="${1:?Use package, verify, archive, or upload}"
shift
cd /tmp
case "$mode" in
  package)
    artifact="${1:?image archive}"; sbom="${2:?SBOM}"; output="${3:?new release directory}"
    test -s "$artifact"; test -s "$sbom"
    mkdir "$output"
    cp "$artifact" "$output/app.tar"
    cp "$sbom" "$output/image.cdx.json"
    cd "$output"
    sha256sum app.tar image.cdx.json > release.sha256
    ;;
  verify)
    cd "${1:?release directory}"
    # Integrity only: this does not authenticate the producer or manifest.
    test -s app.tar; test -s image.cdx.json
    sha256sum app.tar image.cdx.json > /tmp/release-check.$$
    trap 'rm -f /tmp/release-check.$$' EXIT
    cmp release.sha256 /tmp/release-check.$$
    ;;
  archive)
    reports="${1:?report directory}"; output="${2:?output .tar.gz}"
    # The output must be outside the input directory.
    case "$(realpath -m "$output")" in "$(realpath "$reports")"/*) exit 2;; esac
    tar -C "$reports" -czf "$output" .
    ;;
  upload)
    # Generic HTTPS PUT endpoint (for example an internal generic artifact repository).
    # Do not send credentials to redirects or unverified TLS endpoints.
    : "${EVIDENCE_URL:?Set the full HTTPS destination URL}"
    : "${EVIDENCE_TOKEN:?Set an upload-only bearer token}"
    [[ "$EVIDENCE_URL" == https://* ]] || { echo 'HTTPS required' >&2; exit 2; }
    bash "$root/scripts/upload-evidence.sh" "${1:?archive file}"
    ;;
  *) echo "Unknown evidence mode: $mode" >&2; exit 2;;
esac
