#!/bin/sh

source init-kubectl

NODEUID=$(./bin/kubectl get nodes k8stest-control-plane -o jsonpath='{.metadata.uid}')
./bin/kubectl -nspire exec -t deployment/spire-server -- \
    /opt/spire/bin/spire-server entry create \
        -spiffeID spiffe://example.org/workload \
        -parentID "spiffe://example.org/spire/agent/k8s_psat/example-cluster/${NODEUID}" \
        -selector "k8s:container-name:example-workload"

MAXFETCHCHECKS=60
FETCHCHECKINTERVAL=1
for ((i=1; i<=${MAXFETCHCHECKS}; i++)); do
    EXAMPLEPOD=$(./bin/kubectl -nspire get pod -l app=example-workload -o jsonpath="{.items[0].metadata.name}")
    log-info "checking for workload SPIFFE ID ($i of $MAXFETCHCHECKS max)..."
    if ./bin/kubectl -nspire exec -t "${EXAMPLEPOD}" -- \
        /opt/spire/bin/spire-agent api fetch \
            | grep "SPIFFE ID:"; then
        DONE=1
        break
    fi
    sleep "${FETCHCHECKINTERVAL}" 
done

if [ "${DONE}" -eq 1 ]; then
    log-info "SPIFFE ID found."
else
    fail-now "timed out waiting for workload to obtain credentials."
fi
