#!/usr/bin/env bash
#
# The Google Cloud identity Qry runs as: a service account with only the roles
# Qry uses, reached from the cluster through workload identity, so no key is
# stored anywhere. Run by the project's administrator with their own
# `gcloud auth login`.
#
# Usage:
#   ./gcp-service-account.sh --project my-project [--name qry] \
#     [--vertex] [--bigquery-datasets proj:ds1,proj:ds2] \
#     [--namespace qry-app] [--ksa qry-backend-sa] [--apply]
#
# Without --apply it prints every command and changes nothing. Datasets get
# BigQuery Data Viewer one by one, never the whole project; jobs run in
# --project.
#
# Afterwards: `qry doctor --plane prerequisites --gcp-project <p>
# --gcp-service-account <sa> [--gke-cluster <c> --gke-location <l>]`.
set -euo pipefail

PROJECT="" NAME="qry" VERTEX=0 DATASETS="" NAMESPACE="qry-app" KSA="qry-backend-sa" APPLY=0
while [[ $# -gt 0 ]]; do
  case "$1" in
    --project) PROJECT="$2"; shift 2 ;;
    --name) NAME="$2"; shift 2 ;;
    --vertex) VERTEX=1; shift ;;
    --bigquery-datasets) DATASETS="$2"; shift 2 ;;
    --namespace) NAMESPACE="$2"; shift 2 ;;
    --ksa) KSA="$2"; shift 2 ;;
    --apply) APPLY=1; shift ;;
    -h|--help) sed -n '2,19p' "$0"; exit 0 ;;
    *) echo "unknown option $1" >&2; exit 2 ;;
  esac
done
[[ -n "$PROJECT" ]] || { echo "--project is required" >&2; exit 2; }

SA="$NAME@$PROJECT.iam.gserviceaccount.com"
run() {
  echo "+ $*"
  if (( APPLY )); then "$@"; fi
}

echo "# Qry's identity in $PROJECT$( ((APPLY)) || echo ' (dry run: nothing is changed)')"
run gcloud iam service-accounts create "$NAME" --project "$PROJECT" --display-name "Qry"

if (( VERTEX )); then
  run gcloud services enable aiplatform.googleapis.com --project "$PROJECT"
  run gcloud projects add-iam-policy-binding "$PROJECT" --member "serviceAccount:$SA" \
    --role roles/aiplatform.user --condition=None
fi

if [[ -n "$DATASETS" ]]; then
  run gcloud projects add-iam-policy-binding "$PROJECT" --member "serviceAccount:$SA" \
    --role roles/bigquery.jobUser --condition=None
  IFS=, read -ra list <<<"$DATASETS"
  for ds in "${list[@]}"; do
    # BigQuery's own GRANT on a dataset (a "schema" in its SQL): adds one
    # member without touching the dataset's others, and scans no data.
    run bq query --project_id="$PROJECT" --use_legacy_sql=false \
      "GRANT \`roles/bigquery.dataViewer\` ON SCHEMA \`${ds/:/.}\` TO \"serviceAccount:$SA\""
  done
fi

# Workload identity: Qry's pods act as the account without a key. The
# Kubernetes side is the chart's serviceAccount.annotations.
run gcloud iam service-accounts add-iam-policy-binding "$SA" --project "$PROJECT" \
  --role roles/iam.workloadIdentityUser \
  --member "serviceAccount:$PROJECT.svc.id.goog[$NAMESPACE/$KSA]"

cat <<EOF

# For the Helm values:
#   serviceAccount:
#     annotations:
#       iam.gke.io/gcp-service-account: $SA
#
# Then check it:
#   qry doctor --plane prerequisites --gcp-project $PROJECT --gcp-service-account $SA \\
#     --gke-cluster <cluster> --gke-location <region>
EOF
