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

usage() {
  cat <<'EOF'
Usage:
  sudo model-gateway-resolve-model --name FILE.gguf --size BYTES [--mtime UNIX_SECONDS]

Searches common server-local model roots for an exact GGUF filename and size.
The command only prints matching absolute paths; it never copies or modifies
model files.
EOF
}

FILE_NAME=""
FILE_SIZE=""
FILE_MTIME=""

while [[ $# -gt 0 ]]; do
  case "$1" in
    --name)
      FILE_NAME="${2:-}"
      shift 2
      ;;
    --name=*)
      FILE_NAME="${1#*=}"
      shift
      ;;
    --size)
      FILE_SIZE="${2:-}"
      shift 2
      ;;
    --size=*)
      FILE_SIZE="${1#*=}"
      shift
      ;;
    --mtime)
      FILE_MTIME="${2:-}"
      shift 2
      ;;
    --mtime=*)
      FILE_MTIME="${1#*=}"
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Unknown argument: $1" >&2
      usage >&2
      exit 2
      ;;
  esac
done

if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then
  echo "Please run as root." >&2
  exit 1
fi
if [[ -z "$FILE_NAME" || "$FILE_NAME" != "$(basename "$FILE_NAME")" || "${FILE_NAME,,}" != *.gguf ]]; then
  echo "--name must be a GGUF basename." >&2
  exit 2
fi
if [[ ! "$FILE_SIZE" =~ ^[0-9]+$ ]] || [[ "$FILE_SIZE" == "0" ]]; then
  echo "--size must be a positive byte count." >&2
  exit 2
fi
if [[ -n "$FILE_MTIME" && ! "$FILE_MTIME" =~ ^[0-9]+$ ]]; then
  echo "--mtime must be a Unix timestamp in seconds." >&2
  exit 2
fi

roots=(
  /home
  /data
  /mnt
  /media
  /srv
  /opt
  /var/lib/model-gateway
)

count=0
declare -A seen_files=()
for root in "${roots[@]}"; do
  [[ -d "$root" ]] || continue
  while IFS= read -r match; do
    [[ -n "$match" ]] || continue
    if [[ -n "$FILE_MTIME" && "$(stat -Lc '%Y' "$match" 2>/dev/null || true)" != "$FILE_MTIME" ]]; then
      continue
    fi
    identity="$(stat -Lc '%d:%i' "$match" 2>/dev/null || true)"
    if [[ -n "$identity" && -n "${seen_files[$identity]:-}" ]]; then
      continue
    fi
    [[ -n "$identity" ]] && seen_files["$identity"]=1
    printf '%s\n' "$match"
    count=$((count + 1))
    if [[ "$count" -ge 20 ]]; then
      exit 0
    fi
  done < <(
    find "$root" \
      \( -path '*/.local/share/Trash/*' -o -path '*/.Trash-*/*' -o -path '*/.Trash/*' \) -prune -o \
      -type f -name "$FILE_NAME" -size "${FILE_SIZE}c" -print 2>/dev/null
  )
done
