#!/usr/bin/env bash
set -euo pipefail

ROOT="$(git rev-parse --show-toplevel)"
cd "$ROOT"

SOURCE_PATHS=(php db scripts)

echo "[audit] Repo: $ROOT"
echo "[audit] Checking tracking coverage in: ${SOURCE_PATHS[*]}"

untracked="$(git ls-files --others --exclude-standard -- "${SOURCE_PATHS[@]}" || true)"
ignored_all="$(git ls-files --others -i --exclude-standard -- "${SOURCE_PATHS[@]}" || true)"

is_expected_ignored() {
  local path="$1"
  case "$path" in
    */.DS_Store) return 0 ;;
    php/.env) return 0 ;;
    php/public/php_errors.log) return 0 ;;
    php/runtime/*) return 0 ;;
    *) return 1 ;;
  esac
}

ignored=""
if [[ -n "$ignored_all" ]]; then
  while IFS= read -r path; do
    [[ -z "$path" ]] && continue
    if ! is_expected_ignored "$path"; then
      if [[ -z "$ignored" ]]; then
        ignored="$path"
      else
        ignored+=$'\n'"$path"
      fi
    fi
  done <<< "$ignored_all"
fi

status=0

if [[ -n "$untracked" ]]; then
  echo ""
  echo "[audit] Untracked files found under source paths:"
  echo "$untracked"
  status=1
fi

if [[ -n "$ignored" ]]; then
  echo ""
  echo "[audit] Unexpected ignored files found under source paths (review .gitignore rules):"
  echo "$ignored"
  status=1
fi

if [[ $status -ne 0 ]]; then
  echo ""
  echo "[audit] FAILED: source tree is not fully accounted for."
  exit 1
fi

echo "[audit] OK: source paths are fully tracked/accounted for."
