#!/bin/sh

burl="https://launchpad.net/~%s/+sshkeys"                                       

Usage() {
   cat <<EOF
Usage: ${0##*/} user1 [ user2 [ ... ] ]
   Import ssh keys for the user from http://launchpad.net
EOF
}
[ $# -eq 0 ] && { Usage 1>&2; exit 1; }
[ "$1" = "-h" -o "$1" == "--help" ] && { Usage; exit 0; }
cd
umask 066
fail() { echo "$@" 1>&2; exit 1; }
mkdir -m 755 -p .ssh  || { fail "failed to make .ssh dir" 1>&2; exit 1; }

for u in "$@"; do
	url=$(printf "$burl" "$u") &&
		out=$(curl --silent - "$url") ||
		fail "failed to get key for $u [$url]" 1>&2
	# some keys come back with dos line end
	out=$(echo "$out" | sed -e '/^$/d' -e '/^\r/d' \
			-e ':join /=[ ]/!{ N; s/[\n\r]//g ; b join }' \
			 -e 's/[^a-zA-Z0-9@: .\/=+-]//g')
	printf "%s\n" "$out" >> ".ssh/authorized_keys" ||
		fail "failed to write to .ssh/authorized_keys"
	echo "Successfully authorized [$u]"
done

# vi: ts=4 noexpandtab
