#!/usr/bin/env bash
set -euo pipefail
root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
source_dir="$(realpath "${1:?Usage: scan-source.sh SOURCE_DIRECTORY REPORT_DIRECTORY}")"
mkdir -p "${2:?Specify a report directory outside the source tree}"
reports="$(realpath "$2")"
case "$reports/" in "$source_dir/"*) echo 'Reports must be outside the source tree' >&2; exit 2;; esac
export PATH="$root/bin:$PATH"
cache="${TRIVY_CACHE_DIR:-$root/cache/trivy}"
python3 "$root/scripts/check-db-age.py" "$cache"
common=(--cache-dir "$cache" --offline-scan --skip-db-update --skip-java-db-update
        --skip-check-update --skip-version-check --disable-telemetry)
status=0
record() { local rc=0; "$@" || rc=$?; if (( rc != 0 )); then status=1; fi; }
if git -C "$source_dir" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
    if [[ "$(git -C "$source_dir" rev-parse --is-shallow-repository)" == true ]]; then
        echo 'Full Git history is required; unshallow from your internal Gitea server' >&2
        exit 2
    fi
    record gitleaks git "$source_dir" --redact --report-format json --report-path "$reports/gitleaks-history.json"
fi
record gitleaks dir "$source_dir" --redact --report-format json --report-path "$reports/gitleaks-files.json"
record trivy fs "${common[@]}" --scanners vuln,misconfig --severity HIGH,CRITICAL \
    --exit-code 1 --format json --output "$reports/trivy-source.json" "$source_dir"
record trivy fs "${common[@]}" --scanners vuln --format cyclonedx \
    --output "$reports/source.cdx.json" "$source_dir"
exit "$status"
