#!/bin/bash
# if the token is provided, use it. Otherwise, use a password-based 2FA login to Vault and get a time-limited token
function get_token {		
    if [ -z "$VAULT_TOKEN" ]; then
    	echo "No token provided; requesting token [2FA]..."
    	# using password to fetch the token (2FA authentication will be required)
    	read -s -p "Password:" OP_PASSWORD
    	echo
    	VAULT_TOKEN="$("$OP_CURL" --request POST --data "{\"password\":\"$OP_PASSWORD\"}" "$VAULT_ADDR"/v1/auth/ldap-rsi/login/"$OP_NAME" | "$OP_JQ" --raw-output '.auth.client_token')"
    	if [ -z "$VAULT_TOKEN" ]; then
    		echo "Could not get token. Ensure your login credentionals were provided correctly, Vault is accessible (tried: $VAULT_ADDR/v1/auth/ldap-rsi/login/$OP_NAME ) and $OP_JQ is available."
    		exit 1
    	fi
    fi
}