#!/bin/sh

set -exuo pipefail

while ! nc -z -v localhost 8200; do
    echo "Waiting for Vault to start."
    sleep 1
done

echo "Vault is up."

export VAULT_ADDR="http://localhost:8200"
export VAULT_TOKEN="${VAULT_DEV_ROOT_TOKEN_ID}"

vault secrets disable secret
vault secrets enable -version=1 -path=secret kv
# For debugging, enable audit log.
vault audit enable file file_path=/vault/audit.log

# Enable approle for PipeDream to use
vault auth enable approle

# Create permissions and a token for the scheduling service to use.
vault policy write scheduling scheduling_policy.hcl
vault token create -policy=scheduling -id="${VAULT_PIPEDREAM_SCHEDULING_TOKEN}"

# Create user token.
vault policy write user user_policy.hcl
vault token create -orphan -id "${VAULT_USER_TOKEN}" -policy user

echo "Vault initialization complete!"
