#!/usr/bin/env bash
set -euo pipefail

# Generate a new token for Pipedream and writes it to :
# secret/pipedream/dashboard/vault_token
# Requires vault cli 1.3.0+

cleanup() {

    # Cleanup the root token generated
    if [[ ! -z "${VAULT_TOKEN:-}" ]]; then
        echo "Revoking root token."
        vault token revoke $VAULT_TOKEN
    fi

    # Cancel any root token generation in progress due to failure in script
    vault operator generate-root -cancel || :

    unset VAULT_TOKEN
    unset unseal_key
    unset pipedream_vault_token
    unset otp
    unset nonce
}
trap cleanup EXIT

# Auth as yourself to Vault as usual.
echo "Login $USER to Vault:"
vault login -method=ldap username="$USER" > /dev/null

# Generate a OTP for a root token generation.
echo "Generating OTP for root token generation."
otp=$(vault operator generate-root -generate-otp)

# Copy the nonce generated by the following command.
echo "Initializing root token generation with OTP."
nonce=$(vault operator generate-root -init -otp="$otp" | grep "Nonce" | awk '{print $2}')

# Do the following 3 times with 3 different unseal keys.
# The unseal keys are owned by certain Infra members
# (Vince, Terry, Deven, Mike, Kenny, Felix, Ethan, Andres, Himanshu)

echo "To unseal vault need 3 different unseal keys:"
for key_number in 1 2 3
do
    read -s -p "Enter unseal key $key_number (will be hidden):" unseal_key
    echo #so that after user enters we go to new line on console
    if [ "$key_number" -lt 3 ]; then
        echo "$unseal_key" | vault operator generate-root -nonce="$nonce" -
    else
        encoded_root_token=$(echo "$unseal_key" | vault operator generate-root -nonce="$nonce" - | grep "Root Token" | awk '{print $4}')
    fi
done

# The third one should return an "Encoded root token". Decode it with:
echo "Generating root token."
VAULT_TOKEN=$(vault operator generate-root -decode=$encoded_root_token -otp=$otp)
export VAULT_TOKEN

# You should be able to use Vault as root with this env var set.
# Renew PipeDreams token:

# Note the role id.
echo "Fetching RoleID for AppRole."
role_id=$(vault read -field=role_id auth/approle/role/pipedream_dashboard/role-id)

# Note the secret id.
echo "Getting secret issued agains the AppRole."
secret_id=$(vault write -field=secret_id -f auth/approle/role/pipedream_dashboard/secret-id)

# Note the token.
echo "Approle login to get token. "
pipedream_vault_token=$(vault write -field=token auth/approle/login role_id="$role_id" secret_id="$secret_id")

echo "Writing token to Vault."
vault write secret/pipedream/dashboard/vault_token value="$pipedream_vault_token"

echo "Pipedream vault token is succesfully written to Vault"
