#!/usr/bin/env bash
a1="${1:-}"; a2="${2:-}"; a3="${3:-}"; a4="${4:-}"; rest=" $* "
[ "$a1 $a2" = "token issue" ] && exit 0
case "$a1" in
  keypair)
    case "$a2" in show) [ "${KEYPAIR_PRESENT:-0}" = 1 ] && exit 0 || exit 1 ;; create) exit 0 ;; esac; exit 0 ;;
  network)
    case "$a2" in
      show)
        # external network (provider-ext) always present; capi-mgmt-net per NET_PRESENT/marker
        if [ "$a3" = "${EXT_NAME:-provider-ext}" ]; then echo ext-id; exit 0; fi
        { [ "${NET_PRESENT:-0}" = 1 ] || [ -f "${MK_NET:-/x}" ]; } && { echo net-id; exit 0; }; exit 1 ;;
      create) : > "${MK_NET:-/dev/null}" 2>/dev/null; exit 0 ;;
    esac; exit 0 ;;
  subnet)
    case "$a2" in show) [ "${SUBNET_PRESENT:-0}" = 1 ] && exit 0 || exit 1 ;; create) exit 0 ;; esac; exit 0 ;;
  router)
    case "$a2" in
      show)
        if printf '%s' "$rest" | grep -q -- '-f json'; then
          { [ "${GW_PRESENT:-0}" = 1 ] || [ -f "${MK_GW:-/x}" ]; } && echo '{"external_gateway_info":{"network_id":"ext"}}' || echo '{"external_gateway_info":null}'
        elif printf '%s' "$rest" | grep -q -- '-c status'; then
          echo "${ROUTER_STATUS:-ACTIVE}"
        else
          [ "${ROUTER_PRESENT:-0}" = 1 ] && exit 0 || exit 1
        fi
        exit 0 ;;
      create) exit 0 ;;
      set) : > "${MK_GW:?}"; exit 0 ;;
      add) exit 0 ;;
    esac; exit 0 ;;
  security)
    if [ "$a3" = rule ]; then
      case "$a4" in list) [ "${RULES_PRESENT:-0}" = 1 ] && printf '22:22\n6443:6443\n'; exit 0 ;; create) exit 0 ;; esac; exit 0
    fi
    case "$a3" in
      show) { [ "${SG_PRESENT:-0}" = 1 ] || [ -f "${MK_SG:-/x}" ]; } && { echo sg-id; exit 0; }; exit 1 ;;
      create) : > "${MK_SG:?}"; echo sg-id; exit 0 ;;
    esac; exit 0 ;;
esac
exit 0
