#autoload

# Options:
#
# -0        include jid 0 as a match for the host system
# -c        complete configured jails that aren't currently running
# -f file   override config file (default: sysrc -n jail_conf)
# -o param  jail parameter to complete instead of jid -
#              e.g. name, path, ip4.addr, host.hostname

local addhost host param desc=1 configured
local -a jails args expl fopt match mbegin mend
zparseopts -D -K -E 0=addhost c=configured f:=fopt o:=param
param=${param[2]:-name}

jails=( ${${(f)"$(_call_program jails jls $param name)"}/ /:} )

if [[ -n $configured ]]; then
  local jail_conf line f include_pat content
  local -a conf_files cjails running_names raw
  include_pat="(#b)[[:space:]]#.include[[:space:]]##[\"']([^\"']##)[\"']*"

  if (( $#fopt )); then
    jail_conf=${fopt[2]}
  else
    jail_conf=$(_call_program paths sysrc -n jail_conf)
  fi

  # Follow .include directives (accepts both "..." and '...' paths)
  if [[ -r $jail_conf ]]; then
    while IFS= read -r line; do
      [[ $line = ${~include_pat} ]] && conf_files+=( ${~match[1]}(N) )
    done < $jail_conf
    conf_files+=( $jail_conf )
  fi

  # Extract jail block names: lines matching "name {" (optionally indented).
  # Collapse "name\n{" forms to "name {" first so the same pattern catches both.
  for f in ${(u)conf_files}; do
    [[ -r $f ]] || continue
    content=$(< $f)
    content=${content//$'\n'[[:space:]]#\{/' {'}
    raw=( ${(M)${(f)content}:#[[:space:]]#[^#[:space:]]##[[:space:]]#\{*} )
    cjails+=( ${${raw##[[:space:]]#}%%[[:space:]]#\{*} )
  done

  # Replace jails with configured-minus-running; exclude wildcard blocks
  running_names=( ${jails%:*} )
  jails=( ${(u)${cjails:#\*}:|running_names} )
fi

case $param in
  jid) host=0 ;;
  name)
    host=0
    desc=0
  ;;
  path)
    host=/
    args=( -M 'r:|/=* r:|=*' )
  ;;
  ip4.addr) args=( -M 'r:|.=* r:|=*' ) ;;
esac
[[ -n $addhost && -n $host ]] && jails+=( "$host:$HOST" )

if (( desc )); then
  _describe -t jails jail jails "$@" "$args[@]"
else
  _wanted jails expl jail compadd "$@" "$args[@]" - ${jails%:*}
fi
