#! /bin/sh

# A script for upgrading lsh private keys

werror () {
  echo "$1" >&2
}

die () {
  werror "$1"
  exit 1
}

if [ $# -eq 0 ] ; then
  werror "You must supply a key to update, the upgraded key will"
  werror "have the suffix .new."
  werror ""
  werror "Usage: key.."
  exit 1
fi

: ${SEXP_CONV:=sexp-conv}
: ${LSH_DECRYPT_KEY:=lsh-decrypt-key}
: ${LSH_WRITEKEY:=lsh-writekey}

type "$SEXP_CONV" >/dev/null 2>&1 || die "Can't find the sexp-conv program"
type "$LSH_DECRYPT_KEY" >/dev/null 2>&1 || die "Can't find the lsh-decrypt-key program"
type "$LSH_WRITEKEY" >/dev/null 2>&1 || die "Can't find the lsh-writekey program"

for p in $@; do
    werror "Converting key $p"

    keyname="$p"
    crypto="" 
    if "$SEXP_CONV" -s advanced < "$p" \
    | grep 'password-encrypted' >/dev/null; then
      werror "Key is encrypted and must be decrypted."

      "$LSH_DECRYPT_KEY" --in="$p" --out="$p.tmpdecrypted" || \
	 die "Decryption failed for $p, aborting."
      keyname="$p.tmpdecrypted"

      crypto="-c aes256-cbc"
      werror "Key be will be reencryptred using aes256-cbc."
    fi

    # These are the changes we must make:
    #
    # * Numbers are signed, so the most significant bit of all our
    #   numbers must be 0. So we add a leading zero octet to numbers
    #   that need it.

    # It also seems we must reconvert back to transport format to make lsh-writekey

   "$SEXP_CONV" -s hex <"$keyname" \
      | sed -e 's,(\(.\) #\([89a-fA-F]\),(\1 #00\2,' \
      | "$SEXP_CONV" -s transport \
      | "$LSH_WRITEKEY" $crypto -o "$p.new"

    rm -f "$p.tmpdecrypted" "$p.tmpdecrypted.pub" 2>/dev/null
done
