-### Should I start a new agent?
-case "$force,$SSH_AUTH_SOCK" in
- t,* | ,)
- start=t
- ;;
- *)
- start=
- set +e; ssh-add -l >/dev/null 2>&1; rc=$?; set -e
- [ $rc -ge 2 ] && start=t
+## 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