chiark / gitweb /
bin/disorder-notify, dot/e16-bindings: Use `notify-send', not `gdbus'.
[profile] / bin / start-ssh-agent
CommitLineData
285a1386
MW
1#! /bin/sh
2
3set -e
4usage="Usage: $0 [-bc] [COMMAND [ARGS...]]"
5
6### Parse options
7case "${SHELL-/bin/sh}" in
8 *csh*) style=csh;;
9 *) style=sh;;
10esac
af254ca9 11force=nil chosen= commands=
285a1386
MW
12while [ $# -gt 0 ]; do
13 case "$1" in
c388de2b
MW
14 -h | --help) echo "$usage"; exit 0 ;;
15 -c | --cshell | --tcsh) style=csh chosen=t ;;
16 -b | --bourne | --bash | --zsh) style=sh chosen=t ;;
17 -f | --force) force=t ;;
18 --) shift; break ;;
19 -*) echo >&2 "$usage"; exit 1 ;;
20 *) break ;;
285a1386
MW
21 esac
22 shift
23done
24[ $# -gt 0 ] && style=commands
25case $chosen,$style in
26 t,commands)
27 echo >&2 "$0: output style and commands? you're odd"
28 exit 1
29 ;;
30esac
31
b46a2fb2
MW
32## Some useful variables.
33hostname=${HOST-$(hostname)}
3feef411 34user=${USER-${LOGNAME-$(id -un)}} uid=${UID-$(id -u)}
b46a2fb2
MW
35dir=$TMPDIR/.ssh-agent.$hostname.$user
36socket=$dir/sock; pid=$dir/pid
239bb58e 37export SSH_AUTH_SOCK
b46a2fb2 38
3feef411
MW
39## Should I start a new agent?
40foundp=nil
41case $force in
42 nil)
43 case ${SSH_AUTH_SOCK+t} in
44 t)
45 set +e; ssh-add -l >/dev/null 2>&1; rc=$?; set -e
46 if [ $rc -lt 2 ]; then foundp=t; fi
47 ;;
48 esac
49 case $foundp in
50 t) ;;
51 *)
52 for i in \
53 "$HOME/.cache/keyring-"*"/ssh" \
54 "/run/user/$uid/keyring/ssh" \
55 "$socket"
56 do
57 SSH_AUTH_SOCK=$i
58 set +e; ssh-add -l >/dev/null 2>&1; rc=$?; set -e
59 if [ $rc -lt 2 ]; then foundp=t; break; fi
60 done
61 ;;
62 esac
285a1386
MW
63 ;;
64esac
65
66### If so, do that
af254ca9
MW
67case $foundp in
68 nil)
af254ca9 69 mkdir -p -m700 "$dir"
239bb58e 70 SSH_AUTH_SOCK=$socket
f9f7e9df
MW
71 p=$PATH
72 runes=
73 while :; do
74 case $p in *:*) d=${p%%:*} p=${p#*:} ;; *) d=$p p= ;; esac
75 if [ -x "${d+$d/}setsid" ]; then runes="$runes setsid"; break; fi
76 case $p in "") break ;; esac
77 done
af254ca9
MW
78 set +e; ssh-add -l >/dev/null 2>&1; rc=$?; set -e
79 if [ $rc -ge 2 ]; then
80 if [ -f "$pid" ]; then
81 kill $(cat "$pid") >/dev/null 2>&1 || :
82 fi
83 rm -f "$socket" "$pid"
f9f7e9df 84 (cd /; exec $runes ssh-agent -d -a "$socket" </dev/null >/dev/null 2>&1)&
af254ca9 85 echo $! >"$pid"
239bb58e 86 SSH_AUTH_SOCK=$socket
af254ca9
MW
87 fi
88 ;;
89esac
285a1386
MW
90
91### Run a program, or export the details
92case $style in
c388de2b
MW
93 sh) echo "SSH_AUTH_SOCK='$SSH_AUTH_SOCK'; export SSH_AUTH_SOCK" ;;
94 csh) echo "setenv SSH_AUTH_SOCK '$SSH_AUTH_SOCK'" ;;
95 commands) exec "$@" ;;
285a1386 96esac