#!/bin/bash

ME=`basename "$0"`

usage()
{
  cat <<EOF
$ME OLDKEY NEWKEY [USER@]HOST

Replaces the OLDKEY in the authorized keys file of USER at HOST with NEWKEY.
If OLDKEY is "-" just install NEWKEY at HOST.

EOF
}

fatal()
{
  echo >&2 "$1"
  exit 23
}

[ $# -eq 3 ] || { usage ; exit 1 ; }

validate-key()
{
  # Check, that key is
  # - starts with ssh- (is public key)
  # - only one line
  # - is a ssh key
  grep -q '^ssh-' "$1" && \
      [ `wc -l <"$1"` -eq 1 ] && \
      ssh-keygen -lf "$1" >/dev/null || \
      fatal "$1 is not a valid ssh public key/"
}

# Old Key without comment:
if [ "$1" != "-" ] ; then
    validate-key "$1"
    OLDKEY="`sed -n 's/^\(ssh-[^ ]\+ [^ ]\+\).*/\1/p' $1`"
    [ "$OLDKEY" ] || fatal "Could not parse $1."
fi

# New Key including comment:
validate-key "$2"
NEWKEY="`cat $2`"

if [ "$1" == "-" ] ; then
    echo "Installing key for $3..."
    ssh "$3" "if grep -qF \"$NEWKEY\" \"\$HOME/.ssh/authorized_keys\" ; then
                  echo \"The new key is already there -- nothing to do!\"
              else
                echo \"$NEWKEY\" >>\"\$HOME/.ssh/authorized_keys\"
              fi"
elif ssh "$3" "grep -qF \"$OLDKEY\" \"\$HOME/.ssh/authorized_keys\"" ; then
    echo "Replacing key for $3..."
    ssh "$3" "sed -i \"s|$OLDKEY.*|$NEWKEY|\" \"\$HOME/.ssh/authorized_keys\""
else
  echo "Did not find the old key on $3."
  if ssh "$3" "grep -qF \"$NEWKEY\" \"\$HOME/.ssh/authorized_keys\"" ; then
      echo "The new key is already there -- nothing to do!"
  else
    echo "BUT the new key isn't there, too.  Maybe you want to install it?"
  fi
fi
