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

uid="$(id -u)"

linux_sock="/run/user/${uid}/ssh-agent.socket"
darwin_sock="${HOME}/.ssh/agent.sock"

pick_sock=""

# Prefer Linux systemd socket if present
if [[ -S "$linux_sock" ]]; then
  pick_sock="$linux_sock"
elif [[ -S "$darwin_sock" ]]; then
  pick_sock="$darwin_sock"
else
  # Fall back to existing env if it's a socket
  if [[ -n "${SSH_AUTH_SOCK:-}" && -S "${SSH_AUTH_SOCK}" ]]; then
    pick_sock="$SSH_AUTH_SOCK"
  fi
fi

if [[ -z "$pick_sock" ]]; then
  echo "echo 'ERROR: No ssh-agent socket found.' >&2"
  echo "echo 'Tried: $linux_sock and $darwin_sock' >&2"
  echo "return 2 2>/dev/null || exit 2"
  exit 0
fi

cat <<EOF
export SSH_AUTH_SOCK='$pick_sock'
EOF
