#!/usr/bin/env bash
# Local directory or docker archive -> Syft SBOM -> Grype release gate.
set -euo pipefail
root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
kind="${1:?Usage: scan-supply-chain.sh dir|docker-archive INPUT REPORT_DIR}"
[[ "$kind" == dir || "$kind" == docker-archive ]] || exit 2
input="$(realpath "${2:?Missing input}")"
[[ "$kind" != dir || -d "$input" ]] || exit 2
[[ "$kind" != docker-archive || -f "$input" ]] || exit 2
reports="$(realpath -m "${3:?Missing report directory}")"
case "$reports/" in "$input/"*) echo 'Reports must be outside input' >&2; exit 2;; esac
mkdir -p "$reports"
export SYFT_CHECK_FOR_APP_UPDATE=false GRYPE_CHECK_FOR_APP_UPDATE=false
export GRYPE_DB_AUTO_UPDATE=false GRYPE_DB_VALIDATE_AGE=true GRYPE_DB_MAX_ALLOWED_BUILT_AGE=168h
export GRYPE_DB_CACHE_DIR="${GRYPE_DB_CACHE_DIR:-$root/cache/grype}"
# Explicit configurations prevent project-local configuration from disabling the gate.
"$root/bin/grype" -c "$root/examples/grype-offline.yaml" db status -o json > "$reports/grype-db.json"
"$root/bin/syft" scan -c "$root/examples/syft-offline.yaml" "$kind:$input" \
  -o "syft-json=$reports/sbom.syft.json" -o "cyclonedx-json=$reports/sbom.cdx.json"
"$root/bin/grype" -c "$root/examples/grype-offline.yaml" "sbom:$reports/sbom.syft.json" \
  --fail-on high -o json --file "$reports/grype.json"
