#!/usr/bin/env bash
# Lab 14.6 - slopsquatting allow-list gate
# Parses requirements.txt, checks each package against allowed-packages.txt,
# exits non-zero if any unlisted package is found.
#
# Usage: bash ci-example/check-allowlist.sh <path-to-requirements.txt>
#
# Wire into CI as a step before pip install.

set -euo pipefail

REQUIREMENTS="${1:-requirements.txt}"
ALLOWLIST="${2:-ci-example/allowed-packages.txt}"

if [[ ! -f "$REQUIREMENTS" ]]; then
  echo "ERROR: requirements file not found: $REQUIREMENTS"
  exit 1
fi

if [[ ! -f "$ALLOWLIST" ]]; then
  echo "ERROR: allow-list not found: $ALLOWLIST"
  exit 1
fi

FAILED=0

while IFS= read -r line; do
  # Strip version specifiers, extras, and comments
  pkg=$(echo "$line" | sed 's/[>=<!;#].*//' | tr -d ' ' | tr '[:upper:]' '[:lower:]')
  [[ -z "$pkg" ]] && continue

  if ! grep -qiE "^${pkg}$" "$ALLOWLIST"; then
    echo "BLOCKED: '$pkg' is not on the approved allow-list ($ALLOWLIST)"
    FAILED=1
  fi
done < "$REQUIREMENTS"

if [[ "$FAILED" -eq 0 ]]; then
  echo "Allow-list check PASSED: all packages are approved."
fi

exit "$FAILED"
