#!/bin/sh
# vim: ft=sh:fdm=marker:fdl=0:noml:

export RUNNING_AGENT="$(ps ax | grep 'ssh-agent -s' | grep -v grep | wc -l | tr -d '[:space:]')"

# values with escapable characters like spaces need to go here,
# simple single-word values should go in config/environment.d/10-dotfiles.conf

if command -v launchctl >/dev/null 2>&1; then
  # we hardcode /bin/launchctl here,
  # because $PATH briefly lacks /bin
  PATH="$(/bin/launchctl getenv PATH)"
  SSH_AUTH_SOCK="$(/bin/launchctl getenv SSH_AUTH_SOCK)"
  export PATH SSH_AUTH_SOCK
fi
# from: https://github.com/systemd/systemd/issues/7641#issuecomment-355832773
# read environment.d and environment-generator values into session
# (the grep is to skip $'values with whitespace' because they are problematic here)
# shellcheck disable=SC2046
if command -v systemctl >/dev/null 2>&1; then
  export $(systemctl --user show-environment | grep -v "=$'" | xargs)
fi
# TODO: per-session storage/retrieval without `systemctl`

if [ -n "${SSH_AUTH_SOCK}" ]; then
  if echo "${SSH_AUTH_SOCK-}" | grep '^/private/tmp/com.apple.launchd.' >/dev/null; then
    # ignore Apple's `ssh-agent`, because it does not support USB security keys
    unset SSH_AUTH_SOCK
  elif [ ! -w "${SSH_AUTH_SOCK-}" ]; then
    # current SSH socket isn't usable, ditch it
    unset SSH_AUTH_SOCK
  fi
fi

# ----------------------------------------------------------------------------
# osx {{{

# start the daemon here since osx doesnt have windowmanager
gpg-agent --daemon >/dev/null 2>&1
unset SSH_AGENT_PID

# }}}
# ----------------------------------------------------------------------------
# cygwin {{{

env="${HOME}"/.ssh/agent.env

agent_load_env() { test -f "${env}" && . "${env}" >|/dev/null; }

agent_start() {
  (
    umask 077
    ssh-agent -P /usr/bin/winhello.dll >|"${env}"
  )
  . "${env}" >|/dev/null
}

agent_load_env

# agent_run_state: 0=agent running w/ key; 1=agent w/o key; 2= agent not running
agent_run_state=$(
  ssh-add -l >|/dev/null 2>&1
  echo $?
)

if [ -z "${SSH_AUTH_SOCK}" ] || [ "${agent_run_state}" = 2 ]; then
  agent_start
  ssh-add -S /usr/bin/winhello.dll
elif [ -n "${SSH_AUTH_SOCK}" ] && [ "${agent_run_state}" = 1 ]; then
  ssh-add -S /usr/bin/winhello.dll
fi

unset env

# }}}

# shellcheck disable=SC2312
if ! [ -d "/run/user/$(id -u)" ]; then
  # requires ~/.gnupg/S.gpg-agent contains:
  #     %Assuan
  #     socket=/path/to/socket
  # and gnupg >= v2.1.1 for gpg-agent to create the socket in the specified
  # location *and* that /run/user isn't available
  # GPG_AGENT_INFO is only respected by gpg-agent-connect.
  export GPG_AGENT_INFO="${XDG_RUNTIME_DIR}/S.gpg-agent::1"
else
  # if /run/user/$(id -u) is available, newer versions of gpg use it,
  # ignoring any other configuration.
  # shellcheck disable=SC2155
  # export GPG_AGENT_INFO="/run/user/$(id -u)/gnupg/S.gpg-agent::1"
  export GPG_AGENT_INFO="$(gpgconf --list-dirs agent-socket):0:1"
fi

if [ -z "${SSH_AGENT_PID}" ]; then
  if ! [ -e /tmp/ssh-agent-"${LOGNAME:-${USER}}" ]; then
    ssh-agent 2>/dev/null >/tmp/ssh-agent-"${LOGNAME:-${USER}}"
  fi
  # shellcheck disable=SC1090
  . /tmp/ssh-agent-"${LOGNAME:-${USER}}" >/dev/null
fi
if ! ps aux | grep -v grep | grep -q "ssh-agent -s" >/dev/null; then
  eval "$(ssh-agent -s)" >/dev/null
fi

# if grep '^enable-ssh-support' "${GNUPGHOME:-${HOME%/}/.gnupg}"'/gpg-agent.conf' >/dev/null 2>&1; then

# shellcheck disable=SC2312
if [ -z "${SSH_AUTH_SOCK-}" ] && [ -n "$(gpgconf --list-options gpg-agent \
  | awk -F: '/^enable-ssh-support:/{ print $10 }')" ]; then
  if [ "${gnupg_SSH_AUTH_SOCK_by:-0}" -ne $$ ]; then
    # shellcheck disable=SC2155
    export SSH_AUTH_SOCK="$(gpgconf --list-dirs agent-ssh-socket)"
  fi
  gpg-connect-agent updatestartuptty /bye >/dev/null
else
  if [ -z "${GPG_AGENT_INFO-}" ]; then
    agent_sock=$(gpgconf --list-dirs agent-socket)
    export GPG_AGENT_INFO="${agent_sock}:0:1"
    [ -z "${SSH_AUTH_SOCK-}" ] \
      && export SSH_AUTH_SOCK="${XDG_RUNTIME_DIR-}/ssh-agent.socket"
    # export SSH_AUTH_SOCK="${XDG_RUNTIME_DIR-}/gnupg/S.gpg-agent.ssh"
  fi
fi
