c867dc2e9431f6f196d0493c24af5d91f4fba042
[packages/trusty/cirros-testvm.git] / cirros-testvm / src-cirros / src / usr / bin / ssh-add-key
1 #!/bin/sh
2
3 error() { echo "$@" 1>&2; }
4 fail() { [ $# -eq 0 ] || error "$@"; exit 1; }
5
6 Usage() {
7         cat <<EOF
8 Usage: ${0##*/} [ options ] key
9
10    add the key to .ssh/authorized_keys
11    give '-' to read keys from stdin
12
13    options:
14       -p | --prefix STRING  prefix key with STRING
15       -r | --replace        replace any existing entries
16 EOF
17 }
18
19 removekey() {
20         local file="$1" keyline="$2"
21         shift;
22         set -- $keyline
23         sed -i "\\|$2|d" "$file" || return
24 }
25
26 bad_Usage() { Usage 1>&2; [ $# -eq 0 ] || error "$@"; exit 1; }
27
28 short_opts="hpru"
29 long_opts="help,prefix:,replace,user:"
30 getopt_out=$(getopt --name "${0##*/}" \
31         --options "${short_opts}" --long "${long_opts}" -- "$@") &&
32         eval set -- "${getopt_out}" ||
33         bad_Usage
34
35 user=""
36 prefix=""
37 key=""
38 replace=false
39
40 while [ $# -ne 0 ]; do
41         cur=${1}; next=${2};
42         case "$cur" in
43                 -h|--help) Usage ; exit 0;;
44                 -p|--prefix) prefix="$next"; shift;;
45                 -r|--replace) replace=true;;
46                 --) shift; break;;
47         esac
48         shift;
49 done
50
51 [ $# -ge 1 ] || bad_Usage "must provide keys"
52
53 cd ~/ || fail "failed to cd ~"
54 mkdir -p -m 0755 .ssh || fail "failed to make .ssh"
55 umask 066
56 : >> .ssh/authorized_keys ||
57         fail "can't write to ~/.ssh/authorized_keys"
58
59 if [ "$1" = "-" ]; then
60         keys=""
61         key=""
62         # we check for success or non empty string.
63         # on final line with no EOF, it returns 1, but sets key
64         while read key || [ -n "$key" ]; do
65                 keys="${keys}|${key}"
66         done
67         keys=${keys#|};
68         oifs="$IFS"
69         IFS="|"
70         set -- $keys
71         IFS="$oifs"
72 fi
73
74 if $replace; then
75         for key in "$@"; do
76                 removekey ".ssh/authorized_keys" "$key" || fail "failed to remove: $key"
77         done
78 fi
79
80 {
81                 for key in "$@"; do
82                         echo "${prefix:+${prefix} }$key"
83                 done
84 } >> .ssh/authorized_keys
85 chmod 600 .ssh/authorized_keys
86
87 # vi: ts=4 noexpandtab