#!/usr/bin/env bash
set -euo pipefail

# shellcheck source=common.sh
source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/common.sh"

NAME="$SYS_DEBUG_NETWORK_NAME"
SUBNET="$SYS_DEBUG_NETWORK_SUBNET"
GATEWAY="$SYS_DEBUG_NETWORK_GATEWAY"

usage() {
  cat <<EOF
Usage: ${0##*/} [--name NAME] [--subnet CIDR] [--gateway IP]

Create (if missing) the external debug docker network.

Defaults derived from .env or:
  name    = $NAME
  subnet  = $SUBNET
  gateway = $GATEWAY
EOF
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --name)
      shift; [[ $# -gt 0 ]] || { echo "--name requires value" >&2; exit 1; }
      NAME="$1"
      ;;
    --name=*)
      NAME="${1#*=}"
      ;;
    --subnet)
      shift; [[ $# -gt 0 ]] || { echo "--subnet requires value" >&2; exit 1; }
      SUBNET="$1"
      ;;
    --subnet=*)
      SUBNET="${1#*=}"
      ;;
    --gateway)
      shift; [[ $# -gt 0 ]] || { echo "--gateway requires value" >&2; exit 1; }
      GATEWAY="$1"
      ;;
    --gateway=*)
      GATEWAY="${1#*=}"
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Unknown argument: $1" >&2
      usage >&2
      exit 1
      ;;
  esac
  shift
done

require_docker

if docker network inspect "$NAME" >/dev/null 2>&1; then
  log "Network $NAME already exists"
  exit 0
fi

log "Creating network $NAME (subnet=$SUBNET gateway=$GATEWAY)"
docker network create \
  --driver bridge \
  --subnet "$SUBNET" \
  --gateway "$GATEWAY" \
  "$NAME"

mkdir -p "$TMP_DIR"
echo "$NAME" > "$TMP_DIR/network.created"
log "Network $NAME created"
