#!/bin/bash
set -euo pipefail

function require_gotool {
  toolname=$(basename $1)
  if ! ( which ${toolname} >/dev/null 2>&1 ); then
    go version || { echo "${basename} not found and no usable go environment"; exit 1; }
    go get -u $1
  fi
}

require_gotool github.com/Luzifer/vault-user-token

source "${HOME}/.config/vault-user-token"
source "${HOME}/bin/script_framework.sh"

# Check whether a valid token is available
( vault token-lookup >/dev/null 2>&1 ) && exit 0

step "Vault is not authenticated, trying to authenticate... "

# Remove old, invalid token
rm -f "${HOME}/.vault-token"

VUT=$(pgrep -f vault-user-token || echo "" | xargs)
[ -n "$VUT" ] && { step "Killing old vault-user-token processes..."; kill ${VUT}; }

# Start new vault-user-token daemon
vault-user-token --full-hostname=false >/dev/null 2>&1 &
VUT=$!

step "Waiting for token to become available..."
while ! [ -f "${HOME}/.vault-token" ]; do
  # Give the program a moment to get a token
  sleep 0.5

  if ! ( kill -0 $VUT ); then
    fail "vault-user-token exitted, giving up."
  fi
done

( vault token-lookup >/dev/null 2>&1 ) || fail "Vault authentication failed finally"

success "Vault token became available and is valid"