#!/bin/bash

# this is a auth client that expectes keystone app creds loaded into the env
# it will be used by kubectl and automatically get user tokens
# see following for infomation on how to use external authenticator
# https://kubernetes.io/docs/reference/access-authn-authz/authentication/#client-go-credential-plugins

get_keystone_token () 
{ 
    data='{
    "auth": {
        "identity": {
            "methods": [
                "application_credential"
            ],
            "application_credential": {
                "id": "'"${OS_APPLICATION_CREDENTIAL_ID}"'",
                "secret": "'"${OS_APPLICATION_CREDENTIAL_SECRET}"'"
            }
        }
    }
}';
    token=$(curl -k -s -i -H "Content-Type: application/json" -d "${data}" "${OS_AUTH_URL}/auth/tokens" |grep 'X-Subject-Token');
    if [ -z "$token" ]; then
        echo "Invalid authentication information";
    else
        echo $(echo ${token} | awk -F ': ' '{print $2}' | sed -e 's/[[:space:]]*$//');
    fi
}

token=`get_keystone_token`

cat << EOF
{
  "apiVersion": "client.authentication.k8s.io/v1",
  "kind": "ExecCredential",
  "status": {
    "token": "$token"
  }
}
EOF
