#!/bin/sh
  
set -eo pipefail

NOMAD_TOKEN=$1
VAULT_TOKEN=$2

VAULT_ADDR={{ vault_conf.api_addr }}

if [ "$(vault status -format=json | jq .is_self)" != "true" ]; then
  echo "We're not the active vault, exiting"
elif [ "$(vault status -format=json | jq .sealed)" != "false" ]; then
  echo "Vault is sealed, exiting"
elif [ "$(vault status -format=json | jq .initialized)" != "true" ]; then
  echo "Vault is not initialized yet, exiting"
else
  echo Updating Vault certificate to access Nomad API
  VAULT_TOKEN=$VAULT_TOKEN \
    vault write {{ vault_secrets.nomad.secret.path }}/config/access \
      address="{{ vault_secrets.nomad.address }}" \
      token="$NOMAD_TOKEN" \
      ca_cert="$(cat {{ vault_root_dir }}/tls/nomad_ca.crt)" \
      client_cert="$(cat {{ vault_root_dir }}/tls/nomad_client.crt)" \
      client_key="$(cat {{ vault_root_dir }}/tls/nomad_client.key)"
fi
