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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
BIN_PATH="${WORKER_REALESRGAN_BIN:-${ROOT_DIR}/bin/realesrgan-ncnn-vulkan}"
MODEL_DIR="${WORKER_REALESRGAN_MODEL_DIR:-${ROOT_DIR}/models}"

echo "Binary path: ${BIN_PATH}"
echo "Model dir: ${MODEL_DIR}"

if [[ ! -f "${BIN_PATH}" ]]; then
  echo "binary missing"
  exit 1
fi

if [[ ! -x "${BIN_PATH}" ]]; then
  echo "binary exists but is not executable"
  exit 1
fi

if [[ ! -d "${MODEL_DIR}" ]]; then
  echo "model directory missing"
  exit 1
fi

echo "binary exists"
echo "binary executable"

available_models=()
while IFS= read -r param_file; do
  stem="$(basename "${param_file}" .param)"
  if [[ -f "${MODEL_DIR}/${stem}.bin" ]]; then
    available_models+=("${stem}")
  fi
done < <(find "${MODEL_DIR}" -maxdepth 1 -type f -name '*.param' | sort)

if [[ ${#available_models[@]} -eq 0 ]]; then
  echo "no models found"
else
  echo "models listed"
  for model in "${available_models[@]}"; do
    echo " - ${model}"
  done
fi

"${BIN_PATH}" -h >/dev/null 2>&1 || true