#!/usr/bin/env bash
# commands/peer/update-tunnel.sh

function cmd::peer::update_tunnel::on_load() {
  help::section "Target"
  flag::define --name value "desc" label:name section:Filters
  flag::define --type  value "Filter by type"   label:type section:Target
  flag::define --all   bool  "Update all peers"  section:Target

  help::section "Options"
  flag::define --mode value "Tunnel mode" label:mode required choices:split,full section:Options
  flag::define --force bool  "Skip confirmation for --all" section:Options
}

function cmd::peer::update_tunnel::run() {
  flag::parse "$@" || return 1

  local name;  name=$(flag::value --name)
  local type;  type=$(flag::value --type)
  local mode;  mode=$(flag::value --mode)
  local all=false force=false
  flag::bool --all   && all=true
  flag::bool --force && force=true

  [[ -z "$name" && "$all" == "false" ]] && \
    log::error "Specify --name or --all" && return 1

  local allowed_ips
  allowed_ips=$(config::allowed_ips_for "$mode")

  local -a peers=()
  if $all; then
    if ! $force; then
      read -r -p "Update tunnel mode to '${mode}' for ALL peers? [y/N] " confirm
      case "$confirm" in [yY]*) ;; *) log::info "Aborted"; return 0 ;; esac
    fi
    while IFS= read -r conf; do
      peers+=("$(basename "$conf" .conf)")
    done < <(find "$(ctx::clients)" -name "*.conf" 2>/dev/null)
  else
    name=$(peers::resolve_and_require "$name" "$type") || return 1
    peers=("$name")
  fi

  local updated=0
  for peer_name in "${peers[@]}"; do
    local conf
    conf="$(ctx::clients)/${peer_name}.conf"
    [[ ! -f "$conf" ]] && continue
    sed -i "s|^AllowedIPs = .*|AllowedIPs = ${allowed_ips}|" "$conf"
    (( updated++ )) || true
    log::debug "Updated tunnel for: ${peer_name}"
  done

  log::wg_success "Updated tunnel to '${mode}' (${allowed_ips}) for ${updated} peer(s)"
  log::wg "Peers must reconnect to apply the new tunnel mode"
}