#!/bin/bash
set -euo pipefail

if [[ $# -lt 1 ]]
then
    echo "Script requires at least one argument, the robot name"
    exit 1
fi
ROBOT_NAME="$1"
NO_PROMPT="${2:-}"

export VAULT_ADDR=https://vault.zooxlabs.com:8200
vault read secret/hello &> /dev/null || (echo "Vault auth check failed"; exit 1)

for SUFFIX in "" "_host"
do
    SECRET=secret/robot/ssh"$SUFFIX"/$ROBOT_NAME
    echo "Checking secret '$SECRET'"
    set +eo pipefail
    vault read "$SECRET" > /dev/null
    RC="$?"
    set -eo pipefail
    if [[ "$RC" -eq 0 ]]
    then
        echo "Vault secret '$SECRET' already exists; not re-generating"
        continue
    fi

    FILE=/tmp/rsa_"$ROBOT_NAME""$SUFFIX"
    ssh-keygen -b 2048 -t rsa -N "" -C zoox@"$ROBOT_NAME" -f "$FILE"
    if [[ "$SUFFIX" == "" ]]
    then
        echo "======== Begin SSH public key ==========="
        cat "$FILE".pub
        echo "======== End SSH public key ==========="
        if [[ -z "$NO_PROMPT" ]]
        then
            read -p "Contact IT to add the above public key to git. Press ENTER to acknowledge."
        fi
    fi
    vault write "$SECRET" ssh_public_key="`cat "$FILE".pub`"  ssh_private_key="`cat "$FILE"`"
done
