#!/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"

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

Destroy the debug docker network if no containers are attached.
EOF
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --name)
      shift; [[ $# -gt 0 ]] || { echo "--name requires value" >&2; exit 1; }
      NAME="$1"
      ;;
    --name=*)
      NAME="${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 not found; nothing to do"
  exit 0
fi

attached=$(docker network inspect -f '{{range $id, $conf := .Containers}}{{printf "%s " $conf.Name}}{{end}}' "$NAME")
if [[ -n "${attached// }" ]]; then
  echo "[ERR] Cannot remove network $NAME: still connected containers -> $attached" >&2
  exit 1
fi

log "Deleting network $NAME"
docker network rm "$NAME" >/dev/null
rm -f "$TMP_DIR/network.created"
log "Network $NAME removed"
