#!/bin/bash

# This script expects stdin to be the JSON output of Kubernetes nodes, eg:
#  kubectl get nodes -o json

# enumerateCases outputs shell switch statement cases for each node pool
# of the current kubectl context, like:
#
#      my-pool-name-1f57135e-*) echo "us-central1-c" ;;
#      my-pool-name-427cf4f2-*) echo "us-central1-a" ;;
#
function enumerateCases {
  FILTER=$(mktemp)

  cat > $FILTER <<EOF
# Map each node to it's pool, extracted from the node name and label. Eg,
#   {
#     "name": "gke-gazette-us-central1-default-pool-427cf4f2-4glg",
#     "labels": {"failure-domain.beta.kubernetes.io/zone": "us-central1-a", ... }
#      ...
#   }
#
# Would map to:
#   { "pool": "gke-gazette-us-central1-default-pool-427cf4f2-", "zone": "us-central1-a" }
[
  .items[].metadata |
    {
      pool: .name | match("(.*-)[^-]{4}$").captures[0].string,
      zone: .labels["failure-domain.beta.kubernetes.io/zone"]
    }
]

# Group the result on "pool", and pick the first item of each subarray.
| group_by(.pool)[][0]

# Emit interpolated cases.
| "      \(.pool)*) echo \"\(.zone)\" ;; "
EOF

  jq --raw-output --from-file $FILTER
  rm $FILTER
}

# Write a `zonemap` Configmap which contains a `node-zone.sh` script.
# When invoked with a GKE Node name, it outputs its zone.
cat <<EOF
kind: ConfigMap
apiVersion: v1
metadata:
  name: gazette-zonemap
data:
  node-zone.sh: |
    #!/bin/sh
    # This file was generated by generate-zonemap-gke.sh.
    # Do not edit by hand.
    case \$1 in
EOF
enumerateCases
cat <<EOF
      *)
        echo "Unknown pool (re-run generate-zonemap-gke.sh?): \$1";
        exit 1;;
    esac
EOF
