chiark / gitweb /
30c0bc7f5a5a913167dbade4be85f58dddeed91e
[profile] / bin / start-ssh-agent
1 #! /bin/sh
2
3 set -e
4 usage="Usage: $0 [-bc] [COMMAND [ARGS...]]"
5
6 ### Parse options
7 case "${SHELL-/bin/sh}" in
8   *csh*) style=csh;;
9   *) style=sh;;
10 esac
11 force=nil chosen= commands=
12 while [ $# -gt 0 ]; do
13   case "$1" in
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 ;;
21   esac
22   shift
23 done
24 [ $# -gt 0 ] && style=commands
25 case $chosen,$style in
26   t,commands)
27     echo >&2 "$0: output style and commands? you're odd"
28     exit 1
29     ;;
30 esac
31
32 ### Should I start a new agent?
33 case "$force,$SSH_AUTH_SOCK" in
34   t,* | nil,)
35     foundp=nil
36     ;;
37   *)
38     foundp=t
39     set +e; ssh-add -l >/dev/null 2>&1; rc=$?; set -e
40     [ $rc -ge 2 ] && foundp=nil
41     ;;
42 esac
43
44 ### If so, do that
45 case $foundp in
46   nil)
47     hostname=${HOST-$(hostname)}
48     user=${USER-${LOGNAME-$(whoami)}}
49     dir=$TMPDIR/.ssh-agent.$hostname.$user; socket=$dir/sock; pid=$dir/pid
50     mkdir -p -m700 "$dir"
51     SSH_AUTH_SOCK=$socket; export SSH_AUTH_SOCK
52     set +e; ssh-add -l >/dev/null 2>&1; rc=$?; set -e
53     if [ $rc -ge 2 ]; then
54       if [ -f "$pid" ]; then
55         kill $(cat "$pid") >/dev/null 2>&1 || :
56       fi
57       rm -f "$socket" "$pid"
58       (cd /; exec ssh-agent -d -a "$socket" >/dev/null 2>&1)&
59       echo $! >"$pid"
60       SSH_AUTH_SOCK=$socket; export SSH_AUTH_SOCK
61     fi
62     ;;
63 esac
64
65 ### Run a program, or export the details
66 case $style in
67   sh) echo "SSH_AUTH_SOCK='$SSH_AUTH_SOCK'; export SSH_AUTH_SOCK" ;;
68   csh) echo "setenv SSH_AUTH_SOCK '$SSH_AUTH_SOCK'" ;;
69   commands) exec "$@" ;;
70 esac