#!/bin/bash

CLUSTER=$(cd bootstrap && terraform output -raw cluster)
VAULT_TOKEN=$(cd bootstrap && terraform output -raw vault_token)
VAULT_ADDR=$(cd bootstrap && terraform output -raw vault_uri)
MINIO_ADDR=$(cd bootstrap && terraform output -raw minio_uri)
MINIO_SERVER=$(cd bootstrap && terraform output -raw minio_server)
RANCHER_SERVER=$(cd bootstrap && terraform output -raw rancher_uri)

VAULT_ADDR="$VAULT_ADDR" VAULT_TOKEN="$VAULT_TOKEN" vault token renew

MINIO_ACCESS_KEY=$(VAULT_TOKEN="$VAULT_TOKEN" VAULT_ADDR="$VAULT_ADDR" vault kv get -mount="$CLUSTER" -field="access_key" "minio")
MINIO_SECRET_KEY=$(VAULT_TOKEN="$VAULT_TOKEN" VAULT_ADDR="$VAULT_ADDR" vault kv get -mount="$CLUSTER" -field="secret_key" "minio")

cat << EOF > backend.tfvars
endpoints       = { s3 = "${MINIO_ADDR}" }
access_key      = "${MINIO_ACCESS_KEY}"
secret_key      = "${MINIO_SECRET_KEY}"
bucket          = "${CLUSTER}"
key             = "terraform.tfstate"
region          = "eu-central-1"
EOF

cat << EOF > terraform.tfvars
endpoints       = { s3 = "${MINIO_ADDR}" }
access_key      = "${MINIO_ACCESS_KEY}"
secret_key      = "${MINIO_SECRET_KEY}"
bucket          = "${CLUSTER}"
region          = "eu-central-1"
minio_server    = "${MINIO_SERVER}"
rancher_server  = "${RANCHER_SERVER}"
vault_token     = "${VAULT_TOKEN}"
vault_addr      = "${VAULT_ADDR}"
EOF
