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

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

canonical_path() {
  local path="$1"
  local dir
  dir="$(cd "$(dirname "$path")" && pwd -P)"
  printf '%s/%s\n' "$dir" "$(basename "$path")"
}

find_installed_cozy() {
  if [[ -n "${COZY_COMMAND:-}" ]]; then
    printf '%s\n' "$COZY_COMMAND"
    return
  fi
  local candidate=""
  candidate="$(command -v cozy || true)"
  if [[ -n "$candidate" ]]; then
    local self candidate_path
    self="$(canonical_path "$REPO_ROOT/bin/cozy")"
    candidate_path="$(canonical_path "$candidate")"
    if [[ "$candidate_path" != "$self" ]]; then
      printf '%s\n' "$candidate"
      return
    fi
  fi
  return 1
}

if ! cozy_bin="$(find_installed_cozy)"; then
  echo "installed cozy launcher not found" >&2
  echo "Install or expose it on PATH, or set COZY_COMMAND=/path/to/cozy." >&2
  exit 1
fi

exec "$cozy_bin" "$@"
