#!/usr/bin/env bash

set -e

read -p "Hostname: " HOSTNAME
read -p "IP (leave empty tu use hostname): " HOSTIP
if [ -z "${HOSTIP}" ]; then
    HOSTIP=$HOSTNAME
    echo "Using $HOSTIP"
fi
read -p "Username: " USERNAME

PRIVATE_KEY="id_$HOSTNAME"
ENCRYPTED_PRIVATE_KEY="$PRIVATE_KEY.gpg"
PUBLIC_KEY="id_$HOSTNAME.pub"
DECRYPTED=f

if [ ! -f $PRIVATE_KEY ]; then
    DECRYPTED=t
    echo "Decrypting private key ..."
    gpg -d $ENCRYPTED_PRIVATE_KEY > $PRIVATE_KEY
fi

echo "Deploying private key ($PRIVATE_KEY) to ($USERNAME@$HOSTIP) ..."
scp $PRIVATE_KEY $USERNAME@$HOSTIP:.ssh/$PRIVATE_KEY

echo "Deploying public key ($PUBLIC_KEY) to ($USERNAME@$HOSTIP) ..."
scp $PUBLIC_KEY $USERNAME@$HOSTIP:.ssh/$PUBLIC_KEY

if [ "$DECRYPTED" = 't' ]; then
    echo "Deleting decrypted private key ..."
    rm $PRIVATE_KEY
fi

echo "Done"
