#!/usr/bin/env bash

set -euo pipefail

readonly cluster_dir=$1
readonly lokistack_ns=$2
readonly lokistack_name=$3
readonly lokistack_bucket_name=$4

project_id=$(gcloud config get project)
readonly project_id

cluster_name=$(jq -r .clusterName < "$cluster_dir/metadata.json")
readonly cluster_name

sa_name="$cluster_name-$lokistack_ns-$lokistack_name"
export SERVICE_ACCOUNT_NAME="${sa_name:0:30}"

kubectl create sa "$lokistack_name" -n "$lokistack_ns"
kubectl apply -f - <<EOF
apiVersion: v1
kind: Secret
metadata:
  name: $lokistack_name-token
  namespace: $lokistack_ns
  annotations:
    kubernetes.io/service-account.name: $lokistack_name
type: kubernetes.io/service-account-token
EOF

gcloud iam service-accounts create "$SERVICE_ACCOUNT_NAME" \
  --display-name="Loki Operator Account for $cluster_name" \
  --project "$project_id"

service_account_json="$(gcloud iam service-accounts list --format json | jq -r '.[] | select(.name | match("/\(env.SERVICE_ACCOUNT_NAME)@"))')"
readonly service_account_json
service_account_email="$(jq -r .email <<< "$service_account_json")"
readonly service_account_email

readonly subject="system:serviceaccount:$lokistack_ns:$lokistack_name"
project_number=$(gcloud projects describe "$project_id" --format json | jq -r '.projectNumber')
readonly project_number

readonly pool_id="$cluster_name"
readonly provider_id="$cluster_name"
readonly google_application_credentials="/tmp/$SERVICE_ACCOUNT_NAME-application-credentials.json"

while IFS= read -r ROLE_TO_ADD ; do
   gcloud projects add-iam-policy-binding "$project_id" \
     --member="serviceAccount:$service_account_email" \
     --role="$ROLE_TO_ADD" \
     --member="principal://iam.googleapis.com/projects/$project_number/locations/global/workloadIdentityPools/$pool_id/subject/$subject"
done << END_OF_ROLES
roles/iam.workloadIdentityUser
roles/storage.objectAdmin
END_OF_ROLES

gcloud iam workload-identity-pools create-cred-config \
    "projects/$project_number/locations/global/workloadIdentityPools/$pool_id/providers/$provider_id" \
    --service-account="$service_account_email" \
    --credential-source-file=/var/run/secrets/openshift/serviceaccount/token \
    --credential-source-type=text \
    --output-file="$google_application_credentials"

kubectl -n "$lokistack_ns" create secret generic "$lokistack_name-gcp-cloud-credentials" \
    --from-literal=bucketname="$(echo -n "${lokistack_bucket_name}")" \
    --from-file=key.json="$google_application_credentials"
