#!/bin/bash

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
CONFIG_PATH="${ROOT_DIR}/cluster-context/madagascar.json"
CLUSTER_NAME="madagascar"
FORMAT="ip"

usage() {
    cat <<EOF
Usage: $0 [--cluster <name>] [--format ip|name|name=ip]

Reads node information from cluster-context/madagascar.json.
EOF
}

while [[ $# -gt 0 ]]; do
    case "$1" in
        --cluster)
            CLUSTER_NAME="$2"
            shift 2
            ;;
        --format)
            FORMAT="$2"
            shift 2
            ;;
        -h|--help)
            usage
            exit 0
            ;;
        *)
            echo "ERROR: unknown option: $1" >&2
            usage
            exit 1
            ;;
    esac
done

if [[ ! -f "${CONFIG_PATH}" ]]; then
    echo "ERROR: missing cluster config: ${CONFIG_PATH}" >&2
    exit 1
fi

case "${FORMAT}" in
    ip)
        jq -r --arg cluster "${CLUSTER_NAME}" '
            .clusters[$cluster].nodes
            | to_entries[]
            | (
                .value.ip
                // .value.wan.vmbr443.address
                // empty
              )
            | split("/")[0]
        ' "${CONFIG_PATH}"
        ;;
    name)
        jq -r --arg cluster "${CLUSTER_NAME}" '
            .clusters[$cluster].nodes
            | to_entries[]
            | .key
        ' "${CONFIG_PATH}"
        ;;
    name=ip)
        jq -r --arg cluster "${CLUSTER_NAME}" '
            .clusters[$cluster].nodes
            | to_entries[]
            | .key + "=" + ((.value.ip // .value.wan.vmbr443.address // empty) | split("/")[0])
        ' "${CONFIG_PATH}"
        ;;
    *)
        echo "ERROR: unsupported format: ${FORMAT}" >&2
        exit 1
        ;;
esac
