#!/bin/bash

# TODO: check vault endpoints
# assumes availability of vault token and csr/json file
function get_provisioning_cert {
    # ensure that vault and vault token are available
    if [ -z "$VAULT_TOKEN" ]; then
        echo "No Vault access token provided."
        exit 1
    fi
    if [ -z "$VAULT_ADDR" ]; then
        echo "No address for signer (i.e. Vault) provided."
        exit 1
    fi

    # check availability of json file containing the sanitized csr and parameters, store content for later use in web request
    if ! "$OP_CAT" "$CERT_GEN_DIR"/"$OP_NAME".json ; then
        echo "Could not read local JSON file containing CSR. Make sure 'cat' is installed correctly on target and the file is accessible."
        exit 1;
    fi

    OP_PROVISIONING_CERT="$("$OP_CURL" --header "Content-Type: application/json" --header "X-Vault-Token: $VAULT_TOKEN" --request POST --data @"$CERT_GEN_DIR"/"$OP_NAME".json "$VAULT_ADDR"/v1/pki/sign/operator | "$OP_JQ" --raw-output '.data.certificate')"
    if [ -z "$OP_PROVISIONING_CERT" ]; then
        echo "Could not get certificate. Ensure that $VAULT_ADDR/v1/pki/sign/operator is available, the provided token is valid, and the CA chain for Vault's cert is trusted locally."
        exit 1;
    fi
    if ! echo "$OP_PROVISIONING_CERT" > "$CERT_GEN_DIR/$OP_NAME.crt"; then
        echo "Could not write the provisioning certificate file. Check that correct permissions are set for $CERT_GEN_DIR."
        exit 1
    fi

    echo "$OP_PROVISIONING_CERT"
}
