#! /bin/sh set -e usage="Usage: $0 [-bc] [COMMAND [ARGS...]]" ### Parse options case "${SHELL-/bin/sh}" in *csh*) style=csh;; *) style=sh;; esac force=nil chosen= commands= while [ $# -gt 0 ]; do case "$1" in -h | --help) echo "$usage"; exit 0 ;; -c | --cshell | --tcsh) style=csh chosen=t ;; -b | --bourne | --bash | --zsh) style=sh chosen=t ;; -f | --force) force=t ;; --) shift; break ;; -*) echo >&2 "$usage"; exit 1 ;; *) break ;; esac shift done [ $# -gt 0 ] && style=commands case $chosen,$style in t,commands) echo >&2 "$0: output style and commands? you're odd" exit 1 ;; esac ## Check that this stands a chance of working. if ! type >/dev/null 2>&1 ssh-agent || ! type >/dev/null >&1 ssh-add; then echo >&2 "$0: ssh not installed; chickening out" exit 1 fi ## Some useful variables. hostname=${HOST-$(hostname)} user=${USER-${LOGNAME-$(id -un)}} uid=${UID-$(id -u)} dir=$TMPDIR/.ssh-agent.$hostname.$user socket=$dir/sock; pid=$dir/pid export SSH_AUTH_SOCK ## Should I start a new agent? foundp=nil case $force in nil) case ${SSH_AUTH_SOCK+t} in t) set +e; ssh-add -l >/dev/null 2>&1; rc=$?; set -e if [ $rc -lt 2 ]; then foundp=t; fi ;; esac case $foundp in t) ;; *) for i in \ "$HOME/.cache/keyring-"*"/ssh" \ "/run/user/$uid/keyring/ssh" \ "$socket" do SSH_AUTH_SOCK=$i set +e; ssh-add -l >/dev/null 2>&1; rc=$?; set -e if [ $rc -lt 2 ]; then foundp=t; break; fi done ;; esac ;; esac ### If so, do that case $foundp in nil) mkdir -p -m700 "$dir" SSH_AUTH_SOCK=$socket p=$PATH runes= while :; do case $p in *:*) d=${p%%:*} p=${p#*:} ;; *) d=$p p= ;; esac if [ -x "${d+$d/}setsid" ]; then runes="$runes setsid"; break; fi case $p in "") break ;; esac done set +e; ssh-add -l >/dev/null 2>&1; rc=$?; set -e if [ $rc -ge 2 ]; then if [ -f "$pid" ]; then kill $(cat "$pid") >/dev/null 2>&1 || : fi rm -f "$socket" "$pid" (cd /; exec $runes ssh-agent -d -a "$socket" /dev/null 2>&1)& echo $! >"$pid" SSH_AUTH_SOCK=$socket fi ;; esac ### Run a program, or export the details case $style in sh) echo "SSH_AUTH_SOCK='$SSH_AUTH_SOCK'; export SSH_AUTH_SOCK" ;; csh) echo "setenv SSH_AUTH_SOCK '$SSH_AUTH_SOCK'" ;; commands) exec "$@" ;; esac