#!/bin/bash
# if the token is provided, use it. Otherwise, use the cert/key to login to Vault and get a time-limited token
function get_token {
    if [ -z "$VAULT_TOKEN" ]; then
        if [ "$IS_LOCAL" !=  "false" ]; then
            echo "To run provisioning locally on the vehicle, you need a token. Either provide the token using the '-t' or '--token' option or explicitly specify a non-local run of this script on a provisionng machine by using value 'false' (case-sensitive, no quotes) for '-l' or '--local' option."
            exit 1
        fi
        echo "No Token Provided. Connecting to Vault..."
        if [ -z "$VAULT_ADDR" ]; then
            echo "Vault address not specified."
            exit 1;
        fi

        if [ "$OP_TPM" = "false" ]; then
            echo "NOT Using TPM Device..."
            VAULT_TOKEN="$("$OP_CURL" --request POST --cert "$OP_CERT" --key "$OP_KEY" --data "{\"name\":\"$OP_NAME\"}" "$VAULT_ADDR"/v1/auth/cert/login | "$OP_JQ" --raw-output '.auth.client_token')"
            if [ -z "$VAULT_TOKEN" ]; then
                echo "Could not get token (no tpm). Ensure Vault is accessible (tried: $VAULT_ADDR/v1/auth/cert/login ) and $OP_JQ is available."
                exit 1
            fi
        else
            if [ "$OP_TPM" = "true" ]; then
                echo "Using operator's TPM..."
                VAULT_TOKEN="$(OPENSSL_ENGINES="$TPM2TSS_ENGINE" "$OP_CURL" --request POST --cert "$OP_CERT" --engine tpm2tss --key-type ENG --key "$OP_KEY" --data "{\"name\":\"$OP_NAME\"}" "$VAULT_ADDR"/v1/auth/cert/login | "$OP_JQ" --raw-output '.auth.client_token')"
                if [ -z "$VAULT_TOKEN" ]; then
                    echo "Could not get token (no tpm). Ensure Vault is accessible (tried: $VAULT_ADDR/v1/auth/cert/login ) and $OP_JQ is available."
                    exit 1
                fi
            else
                echo "Invalid value for option '--with-tpm'. Valid values are only 'true' or 'false', case-sensitive and without the single-quotes"
                exit 1
            fi
        fi
    echo "Done"
    fi
    echo "Using Token: $VAULT_TOKEN"
}
