#!/usr/bin/env bash
# SBOM (Software Bill of Materials) generator for projects.
# Uses syft for container images and npm/pip for package manifests.
# Usage: bash scripts/generate_sbom.sh [--path /project] [--format cyclonedx-json]
set -euo pipefail

PROJECT_PATH="${1:-.}"
FORMAT="${2:-cyclonedx-json}"

echo "=== SBOM Generation: $PROJECT_PATH ==="
echo "Format: $FORMAT"
echo ""

# Try syft first (best coverage)
if command -v syft &>/dev/null; then
  echo "Using syft..."
  syft "$PROJECT_PATH" -o "$FORMAT" 2>/dev/null
  exit $?
fi

# Fallback: language-specific
echo "syft not found, using fallback detection..."
echo ""

if [ -f "$PROJECT_PATH/package.json" ]; then
  echo "--- npm dependencies ---"
  cd "$PROJECT_PATH"
  npm ls --all --json 2>/dev/null || npm ls --json 2>/dev/null
elif [ -f "$PROJECT_PATH/requirements.txt" ]; then
  echo "--- Python dependencies ---"
  echo '{"components": ['
  while IFS= read -r line; do
    pkg=$(echo "$line" | sed 's/[>=<].*//' | tr -d ' ')
    ver=$(echo "$line" | grep -oP '[\d.]+' | head -1)
    [ -n "$pkg" ] && echo "  {\"name\": \"$pkg\", \"version\": \"${ver:-unknown}\", \"type\": \"library\"},"
  done < "$PROJECT_PATH/requirements.txt"
  echo ']}'
elif [ -f "$PROJECT_PATH/pyproject.toml" ]; then
  echo "--- pyproject.toml dependencies ---"
  grep -A100 '\[project\]' "$PROJECT_PATH/pyproject.toml" | grep -A50 'dependencies' | head -30
elif [ -f "$PROJECT_PATH/go.mod" ]; then
  echo "--- Go modules ---"
  cat "$PROJECT_PATH/go.mod"
else
  echo "No recognized package manifest found."
  echo "Install syft for universal SBOM generation: https://github.com/anchore/syft"
  exit 1
fi
