#!/usr/bin/env bash
# commands/block/show.sh

function cmd::block::show::on_load() {
  help::section "Target"
  flag::define --name       value "Peer name to block"          label:name     section:Target
  flag::define --identity   value "Block all peers in identity" label:identity section:Target
  flag::define --type       value "Filter by device type"       label:type     section:Target

  help::section "Rules"
  flag::define --ip[]          "Block specific IP"                    label:ip        section:Rules
  flag::define --subnet[]      "Block specific subnet"                label:subnet    section:Rules
  flag::define --port[]        "Block specific port (ip:port:proto)"  label:port      section:Rules
  flag::define --service[]     "Block by service name"                label:service   section:Rules
  flag::define --block-name value "Label for this block rule"         label:name      section:Rules

  help::section "Options"
  flag::define --reason value "Reason for block (recorded in history)" label:reason section:Options
  flag::define --force  bool  "Skip confirmation"               section:Options
  flag::define --quiet  bool  "Suppress output"                 section:Options

  flag::exclusive --name --identity
}

function cmd::block::show::run() {
  flag::parse "$@" || return 1

  local name;       name=$(flag::value --name)
  local identity;   identity=$(flag::value --identity)
  local type;       type=$(flag::value --type)
  local block_name; block_name=$(flag::value --block-name)
  local reason;     reason=$(flag::value --reason)
  local quiet=false force=false
  flag::bool --quiet && quiet=true
  flag::bool --force && force=true

  # Array flags
  local -a ips=() subnets=() ports=() services=()
  while IFS= read -r v; do [[ -n "$v" ]] && ips+=("$v");      done < <(flag::array --ip)
  while IFS= read -r v; do [[ -n "$v" ]] && subnets+=("$v");  done < <(flag::array --subnet)
  while IFS= read -r v; do [[ -n "$v" ]] && ports+=("$v");    done < <(flag::array --port)
  while IFS= read -r v; do [[ -n "$v" ]] && services+=("$v"); done < <(flag::array --service)

  # Require --name or --identity
  if [[ -z "$name" && -z "$identity" ]]; then
    log::error "Missing required flag: --name or --identity"
    return 1
  fi

  cmd::block::_impl \
    "$name" "$identity" "$type" "$block_name" "$reason" \
    "$quiet" "$force" \
    ips subnets ports services
}