#!/usr/bin/env bash
# Delete files from an extracted /config tree that match
# services/home-assistant/.gitignore patterns.
#
# Intentionally NOT a full gitignore engine — the exclusion list is small
# and fixed (see DESIGN.md, "Scope"), so each line is applied as either a
# directory-name prune (trailing "/") or a path/basename glob.
set -euo pipefail

apply_gitignore_filter() {
  local root_dir="$1"
  local gitignore_file="$2"

  if [[ ! -f "$gitignore_file" ]]; then
    echo "apply_gitignore_filter: gitignore file not found: $gitignore_file" >&2
    return 1
  fi

  local pattern
  while IFS= read -r pattern; do
    [[ -z "$pattern" || "$pattern" == \#* ]] && continue

    if [[ "$pattern" == */ ]]; then
      local dirname="${pattern%/}"
      find "$root_dir" -type d -name "$dirname" -prune -exec rm -rf {} +
    elif [[ "$pattern" == */* ]]; then
      # path-relative pattern, e.g. ".storage/auth*"
      find "$root_dir" -type f -path "*/${pattern}" -delete
    else
      find "$root_dir" -type f -name "$pattern" -delete
    fi
  done < "$gitignore_file"
}
