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

function cmd::unblock::show::on_load() {
  help::section "Target"
  flag::define --name     value "Peer name to unblock"              label:name        section:Target
  flag::define --identity value "Unblock 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[]       "Unblock specific IP"                   label:ip          section:Rules
  flag::define --subnet[]   "Unblock specific subnet"               label:subnet      section:Rules
  flag::define --port[]     "Unblock specific port (ip:port:proto)" label:port        section:Rules
  flag::define --service[]  "Unblock by service name"               label:service     section:Rules
  flag::define --all  bool  "Unblock all rules"                                       section:Rules

  help::section "Options"
  flag::define --reason value "Reason for unblock (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::unblock::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 reason;   reason=$(flag::value --reason)
  local all=false quiet=false force=false
  flag::bool --all   && all=true
  flag::bool --quiet && quiet=true
  flag::bool --force && force=true

  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)

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

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