#!/bin/sh

# Roughly based on this article:
# https://werat.github.io/2017/02/04/tmux-ssh-agent-forwarding.html

REMOTE_LINK="${HOME}/.ssh/ssh_auth_sock"

if [ -S "${SSH_AUTH_SOCK}" ] ; then
  SSH_REMOTE_AUTH_SOCK="${SSH_AUTH_SOCK}"
  export SSH_REMOTE_AUTH_SOCK
  # Always update the symlink to the latest session's socket.
  # This ensures that tmux (which uses the static path) always points to a
  # current agent.
  mkdir -p "$(dirname "${REMOTE_LINK}")"
  ln -sf "${SSH_AUTH_SOCK}" "${REMOTE_LINK}"
  SSH_AUTH_SOCK="${REMOTE_LINK}"
  export SSH_AUTH_SOCK
fi

# if stdin is a tty, don't do the cookie step
if [ ! -t 0 ] ; then
  # Handle X forwarding, per sshd(8)
  if read -r proto cookie && [ -n "$DISPLAY" ]; then
    if [ "$(echo "$DISPLAY" | cut -c1-10)" = 'localhost:' ]; then
      # X11UseLocalhost=yes
      echo add "unix:$(echo "$DISPLAY" | cut -c11-)" "$proto" "$cookie"
    else
      # X11UseLocalhost=no
      echo add "$DISPLAY $proto $cookie"
    fi | xauth -q -
  fi
fi
