#!/bin/sh -

case "$RSHCMD" in
*ssh*\ *)	;;
*)		RSHCMD='ssh -q -x';;
esac

# sshauth - (de)authorize ssh access to the given hosts
# Steve Kinzler, steve@kinzler.com, Jan 16/Nov 19/Jun 21
# https://kinzler.com/me/home.html#unix

# compare to ssh-copy-id from openssh-client

del=; quiet=; pub=; key=
while :
do
	case $# in
	0)	break;;
	*)	case "$1" in
		-d)	del="$1";;
		-q)	quiet="$1";;
		-f)	shift; pub="$1"
			case "$pub" in
			-)	;;
			*)	test -r "$pub" || bad=t;;
			esac;;
		-k)	key="$1";;

		--)	shift; break;;
		-h)	bad=t; break;;
		-*)	bad=t; echo "$0: unknown option ($1)" 1>&2;;
		*)	break;;
		esac
		shift;;
	esac
done

prvfile="${HOME_SU-$HOME}"/.ssh/id_rsa
pubfile="$prvfile".pub

case "$bad" in
?*)	cat << EOF 1>&2
usage: $0 [ -d ] [ -q ] [ -f file ] [ -k ]
	[ host | user@host ] ...
	-d	don't append rather delete the ssh public key
	-q	quiet mode, don't report hosts as being authorized
	-f	use the given file instead of your default ssh public key,
		  may be - to indicate standard input
	-k	output the public key to be used
Appends your ssh public key ($pubfile) to all
the given ssh destinations' .ssh/authorized_keys, if not already
there.  This key file is generated if it doesn't already exist.
EOF
	exit 1;;
esac

case "$pub" in
?*)	pubkey=`cat "$pub"`;;
*)	case "$del" in
	?*)	echo "$0: aborting, no public key to delete" 1>&2; exit 3;;
	esac
	test ! -r "$pubfile" && ssh-keygen -t rsa -f "$prvfile"
	pubkey=`cat "$pubfile"`;;
esac
test -n "$key" && echo "$pubkey"

set `echo "$pubkey" | wc` "$@"
if test "$1" -ne 1 -o "$2" -ne 3 -o "$3" -lt 200 ||
   echo "$pubkey" | grep -s "['"'")]' > /dev/null
then
	echo "$0: aborting, does not look like a public key line ($pubkey)" \
		1>&2; exit 2
fi
shift; shift; shift

for host
do
	case "$del" in
	?*)	test -z "$quiet" && echo "deauthorizing $host ..."
		${RSHCMD-ssh} "$host" "
			test -e .ssh/authorized_keys || exit
			perl -ni -e 'chomp(\$l = \$_); \
				     print if \$l ne q($pubkey)' \
				.ssh/authorized_keys";;

	*)	test -z "$quiet" && echo "authorizing $host ..."
		${RSHCMD-ssh} "$host" "
			mkdir -p .ssh; chmod 700 .ssh
			grep -s '$pubkey' .ssh/authorized_keys > /dev/null || \
				echo '$pubkey' >> .ssh/authorized_keys";;
	esac
done
