#!/usr/bin/env bash
# R01-N16 — surface known CVEs in the locked composer dependencies.
#
# Runs `composer audit` against composer.lock inside the project's runtime
# image, so the audit reflects the exact versions the running container
# has. Intended for periodic operator use (e.g. weekly cron) and as a
# pre-deploy gate after `git pull`.
#
# Exit status mirrors composer's: 0 = clean, non-zero = advisories found
# (or composer itself errored). Operators can pipe to `mail` / `wall` etc.

set -euo pipefail

# Resolve repo root so the script works regardless of cwd.
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)"
REPO_ROOT="$(cd -- "${SCRIPT_DIR}/.." &>/dev/null && pwd)"
cd "${REPO_ROOT}"

IMAGE="${SPRINT_PLANER_IMAGE:-sprint_planer_web-app:latest}"

if ! command -v docker >/dev/null 2>&1; then
    echo "audit.sh: docker is required (composer + the right ext-* set live in the image)" >&2
    exit 2
fi

if ! docker image inspect "${IMAGE}" >/dev/null 2>&1; then
    echo "audit.sh: image '${IMAGE}' not found locally — run 'docker compose build' first" >&2
    exit 2
fi

exec docker run --rm \
    -v "${REPO_ROOT}:/app" \
    -w /app \
    "${IMAGE}" \
    sh -c "git config --global --add safe.directory /app && composer audit --locked --no-interaction"
