#!/usr/bin/env bash
# fake openstack: network/subnet show|create|set. Stateful via markers so create->confirm works.
obj="${1:-}"; act="${2:-}"; rest=" $* "
present() {
  case "$1" in
    net) [ -f "${NET_MARKER:-/nonexistent}" ] || [ "${NET_PRESENT:-0}" = 1 ] ;;
    sub) [ -f "${SUB_MARKER:-/nonexistent}" ] || [ "${SUB_PRESENT:-0}" = 1 ] ;;
  esac
}
case "$obj $act" in
  "network show")
    if present net; then
      if printf '%s' "$rest" | grep -q -- '-f json'; then
        sh=false; [ "${BAD_SHARED:-0}" = 1 ] && sh=true
        printf '{"name":"provider-ext","router:external":true,"provider:network_type":"flat","provider:physical_network":"physnet1","shared":%s,"tags":["role=provider"]}\n' "$sh"
      else echo "net-id"; fi
      exit 0
    fi
    exit 1 ;;
  "network create") : > "${NET_MARKER:?}"; echo "net-id"; exit 0 ;;
  "network set") exit 0 ;;
  "subnet show")
    if present sub; then
      if printf '%s' "$rest" | grep -q -- '-f json'; then
        printf '{"name":"provider-ext-fip","cidr":"10.12.4.0/22","gateway_ip":"10.12.4.1","enable_dhcp":false,"allocation_pools":[{"start":"10.12.5.0","end":"10.12.7.254"}],"tags":["role=provider"]}\n'
      else echo "sub-id"; fi
      exit 0
    fi
    exit 1 ;;
  "subnet create") : > "${SUB_MARKER:?}"; echo "sub-id"; exit 0 ;;
  "subnet set") exit 0 ;;
esac
exit 0
