#!/usr/bin/env bash

set -euo pipefail

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

if ! [[ -d "$cluster_dir/cco"  ]]; then
    echo "Cluster not managed with Azure Workload Identity Federation"
    exit 1
fi

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

region=$(jq -r .azure.region < "$cluster_dir/metadata.json")
readonly region

metadata_rgn=$(jq -r .azure.resourceGroupName < "$cluster_dir/metadata.json")
readonly metadata_rgn

readonly resource_group_name="$metadata_rgn-oidc"

subscription_id="$(az account show | jq -r '.id')"
readonly subscription_id

readonly identity_name="$cluster_name-$lokistack_ns-$lokistack_name-azure-cloud-credentials"
readonly subject="system:serviceaccount:$lokistack_ns:$lokistack_name"

cluster_issuer="$(jq -r '.issuer' $cluster_dir/cco/openid-configuration)"
readonly cluster_issuer

echo "Creating managed identity '$identity_name' in resource group '$resource_group_name'..."
az identity create \
   --name "$identity_name" \
   --resource-group "$resource_group_name" \
   --location "$region" \
   --subscription "$subscription_id" | jq

echo "Creating federated credentials for managed identity '$identity_name' in resource group '$resource_group_name'..."
az identity federated-credential create \
   --name openshift-logging-lokistack \
   --identity-name "$identity_name" \
   --resource-group "$resource_group_name" \
   --issuer "$cluster_issuer" \
   --subject "$subject" \
   --audiences "openshift" | jq

role_id=$(az role definition list --custom-role-only true --output json | jq -r --arg idName "$identity_name" '.[] | select(.roleName == $idName) | .id')

if ! [[ "$role_id" == "" ]]; then
    echo "Creating custom role for '$identity_name' granting access to all Microsoft.Storage/*/{read,delete,write} resources..."
    cat > "/tmp/$identity_name-azure-access.json" << EOF
{
  "Name": "$identity_name",
  "IsCustom": true,
  "Description": "Can access content on Azure Storage containers.",
  "Actions": [
    "Microsoft.Storage/*/read",
    "Microsoft.Storage/*/delete",
    "Microsoft.Storage/*/write"
  ],
  "NotActions": [],
  "AssignableScopes": [
    "/subscriptions/$subscription_id"
  ]
}
EOF
    az role definition delete --name "$identity_name"
    az role definition create --role-definition @"/tmp/$identity_name-azure-access.json" | jq
fi

assignee_name=$(az ad sp list --all --filter "servicePrincipalType eq 'ManagedIdentity'" | jq -r --arg idName "$identity_name" '.[] | select(.displayName == $idName) | .appId')
readonly assignee_name
readonly role_id

echo "Assigning role '$identity_name' managed identity's '$identity_name' service principal '$assignee_name'"
az role assignment create \
   --assignee "$assignee_name" \
   --role "$role_id" \
   --scope "/subscriptions/$subscription_id" | jq
