# -*- mode: sh; sh-shell: bash -*-
# vim: set ft=bash:
# shellcheck shell=bash

### Provides help, extracts documentation from modules
###
### Inline documentation uses two or three hash characters. Three '###' is used for file level
### documentation to describe a file entirely. Two '##' are used in different contexts:
###
### Variable definitions that use the 'declare' keyword can use '##' at the end of the same
### line to document the variable.
###
### Functions use formal parameter syntax: 'function name ## [--opt] <required> [optional] - description'
### Parameters use: <mandatory>, [optional], param.., [param..], --flags, foo|bar alternatives.
### Multi-line documentation continues on following lines starting with optional whitespace
### followed by '##' and parameter explanations.
###
### Rules are documented by '##' lines before the rule definition, using the same formal
### parameter syntax when the rule accepts parameters.
###
### Only variables, functions and rules that have doc comments are included in the output.

# prototype: "topic" = "help"
# prototype: "rule" = "help"
# prototype: "function" = "help"
# prototype: "variable" = "help"
# prototype: "-s" = "literal -s"
# prototype: "--short" = "literal --short"

function help
{
  local -a args=("$@")
  local section_only=0

  if (( ${#args[@]} > 0 )); then
    case "${args[0]}" in
      -s|--short)
        section_only=1
        args=("${args[@]:1}")
        ;;
    esac
  fi

  local query="${args[*]}"
  if [[ -z "$query" ]]; then
    section_only=0
  fi

  local force_pager="${BAR_FORCE_PAGER:-}"
  local pager=""
  local -a pager_cmd=()
  local pager_available=1
  local use_pager=1
  local stdout_is_tty=1
  [[ -t 1 ]] || stdout_is_tty=0

  if [[ -n "$force_pager" ]]; then
    case "$force_pager" in
      less)
        if is_command_installed less; then
          pager="less"
        else
          pager_available=0
        fi
        ;;
      more)
        if is_command_installed more; then
          pager="more"
        else
          pager_available=0
        fi
        ;;
      *)
        pager_available=0
        ;;
    esac
  else
    if is_command_installed less; then
      pager="less"
    elif is_command_installed more; then
      pager="more"
    else
      pager_available=0
    fi
  fi

  if [[ "$pager" == "less" ]]; then
    pager_cmd=(less -R -F)
  elif [[ "$pager" == "more" ]]; then
    pager_cmd=(more)
  fi

  if [[ $stdout_is_tty -eq 0 || $pager_available -eq 0 ]]; then
    use_pager=0
  fi

  local target_line=""
  local search_term=""
  local case_sensitive=0
  local found_line=""
  local found_span=""
  local found_proto=""
  local best_rank=9999
  local best_line=""
  local best_span=""
  local best_proto=""

  if [[ -n "$query" ]]; then
    # Smart case: if query contains any uppercase letter -> case-sensitive search
    case_sensitive=0
    if [[ "$query" =~ [A-Z] ]]; then
      case_sensitive=1
    fi

    local entry span remainder value proto start_line lineno
    local lower_query="${query,,}"

    # Iterate index (which preserves case) and perform a prefix match.
    while IFS= read -r entry; do
      [[ -z "$entry" ]] && continue
      span="${entry%%:*}"
      remainder="${entry#*:}"
      proto="${remainder%%:*}"
      value="${remainder#*:}"
      [[ -z "$value" ]] && continue

      start_line="${span%%-*}"
      if [[ "$start_line" =~ ^[0-9]+$ ]]; then
        lineno="$start_line"
      else
        continue
      fi

      # Escape regex metacharacters in query for safe use in =~
      local q_escaped
      q_escaped=$(printf '%s' "$query" | sed -e 's/[]\\.^$*+?()[\]{}|]/\\&/g')

      local matched=0
      local match_exact=0
      local begins_value=0

      if (( case_sensitive == 1 )); then
        if [[ "$value" =~ (^|[^[:alnum:]])$q_escaped ]]; then
          matched=1
          if [[ "$value" == "$query" ]]; then
            match_exact=1
          fi
          if (( ${#value} >= ${#query} )) && [[ "${value:0:${#query}}" == "$query" ]]; then
            begins_value=1
          fi
        fi
      else
        local lower_value lower_q_escaped
        lower_value="${value,,}"
        lower_q_escaped=$(printf '%s' "${q_escaped,,}")
        if [[ "$lower_value" =~ (^|[^[:alnum:]])$lower_q_escaped ]]; then
          matched=1
          if [[ "$lower_value" == "$lower_query" ]]; then
            match_exact=1
          fi
          if (( ${#lower_value} >= ${#lower_query} )) && [[ "${lower_value:0:${#lower_query}}" == "$lower_query" ]]; then
            begins_value=1
          fi
        fi
      fi

      if (( matched == 0 )); then
        continue
      fi

      local rank
      case "$proto" in
        topic) rank=100 ;;
        function) rank=200 ;;
        rule) rank=300 ;;
        variable) rank=400 ;;
        *) rank=500 ;;
      esac

      if (( begins_value == 1 )); then
        (( rank -= 20 ))
      fi

      if (( match_exact == 1 )); then
        (( rank -= 10 ))
      fi

      if (( rank < best_rank || (rank == best_rank && lineno < best_line) )); then
        best_rank=$rank
        best_line="$lineno"
        best_span="$span"
        best_proto="$proto"
      fi

      if (( rank <= 90 )); then
        # Exact topic match (or better) cannot be improved further
        break
      fi
    done < <(help_indexer)

    if [[ -n "$best_line" ]]; then
      found_line="$best_line"
      found_span="$best_span"
      found_proto="$best_proto"
    fi

    if [[ -n "$found_line" ]]; then
      target_line="$found_line"
    else
      # Not found in index -> forward as text search to pager
      # Escape forward slashes for pager search patterns
      search_term="${query//\//\\/}"
    fi
  fi

  local render_span=""
  if (( section_only == 1 )); then
    if [[ -n "$found_line" && "$found_proto" != "text" ]]; then
      render_span="$found_span"
      target_line=""
      search_term=""
    else
      section_only=0
    fi
  fi

  if [[ $use_pager -eq 0 ]]; then
    if [[ -n "$render_span" ]]; then
      help_render "$render_span"
      return
    fi
    if (( stdout_is_tty == 0 )); then
      local -a help_lines=()
      mapfile -t help_lines < <(help_render)

      local total=${#help_lines[@]}
      if (( total == 0 )); then
        return
      fi

      local start_idx=0
      if [[ -n "$target_line" && "$target_line" =~ ^[0-9]+$ ]]; then
        local idx=$(( target_line - 1 ))
        if (( idx >= 0 && idx < total )); then
          start_idx=$idx
        fi
      fi

      if (( start_idx < 0 || start_idx >= total )); then
        start_idx=0
      fi

      local i
      for ((i=start_idx; i<total; i++)); do
        printf '%s\n' "${help_lines[i]}" || return 0
      done
      return
    fi

    if [[ -n "$render_span" ]]; then
      help_render "$render_span"
    else
      help_render
    fi
    return
  fi

  if [[ -n "$target_line" ]]; then
    pager_cmd+=("+$target_line")
  elif [[ -n "$search_term" ]]; then
    # Only include case-insensitive flag for less when we used smart-case (case-insensitive)
    if [[ "$pager" == "less" ]]; then
      if [[ "$case_sensitive" -eq 0 ]]; then
        pager_cmd+=(-I "+/${search_term}")
      else
        pager_cmd+=("+/${search_term}")
      fi
    else
      pager_cmd+=("+/${search_term}")
    fi
  fi

  if (( ${#pager_cmd[@]} == 0 )); then
    if [[ -n "$render_span" ]]; then
      help_render "$render_span"
    else
      help_render
    fi
    return
  fi

  # shellcheck disable=2034
  BAR_VERBOSITY_LEVEL=0
  if [[ -n "$render_span" ]]; then
    "${pager_cmd[@]}" < <(help_render "$render_span")
  else
    "${pager_cmd[@]}" < <(help_render)
  fi
}

# Help text formatting rules:
# - Basic identation step is 2 spaces
# - Normal text indentation is a even number of spaces
# - Code segments are indented by a odd number of spaces.
# - Major headers have 2 empty lines above and one empty line behind.
# - Topevel headers (at column 0) are ALL UPPERCASE. With the following section idented.
# - Quote blocks like the 'LICENSE' at the end use one extra indentation level.
# - Lists start at the same indentation level as the text.
function help_render
{
  local span="${1:-}"
  if ! declare -p help_render_cache >/dev/null 2>&1; then
    declare -ga help_render_cache=()
  mapfile -t help_render_cache <<EOF

  bar -- BAshRulez the bash rule evaluator

ABOUT

  Bar is a command runner that determines the order of commands and which ones to run, based
  on rules. It lets the user define rules that dependently and conditionally evaluate shell
  statements.  This is similar to other tools such as 'make' or 'just' but adds some
  opinionated differences. There is support for using bar as driver for githooks for
  automating workflows.

  The notable differences to other similar tools are:

  * Rules in bar can have multiple clauses.
  * Normally rules are conjunctive, when a clause of a rule fails then the rule fails and not
    further evaluated.
  * Rules can be made disjunctive, then a rule succeeds on the first succeeding clause.
  * Clauses can be conditionally skipped.
  * The results of rules are cached. Normally rules are evaluated only once, although there is
    a form to define rules that always evaluate.
  * We have a module that can memorize commands persistently and schedule evaluation to the
    background. A later instance can pick up the results from this background evaluation.

  When you read this because you have seen 'bar' or '.bar' used in a repository then you may
  look at INITIAL INSTALLATION below.


QUICKSTART

  When you cloned a project that uses bar then you can:

   ./bar                # just runs whatever the maintainer decided as default
   ./bar watch          # watches the project for changes and runs the default
   ./bar watch fastchk  # watches the project for changes and runs fast checks
   ./bar activate       # installs githooks and other local prep work

  When you want to install and use it in your own projects:

   git clone https://seed.pipapo.org/z3WhBdHt1VVNyeQ61zpY66pNzuSrP.git bar
   cd bar
   ./bar init_install ~/.local/
   git pull   # to get updates

  Then you can initialize it in your projects with:

   bar init
   git add Barf Bar.d .gitignore
   git commit -m 'start using bar'

   bar init_update  # for updating the version stored in the project

  The second personality of bar is 'please' eg.:

   please wake <hostname>     # sends a wake-on-lan packet to a host
   please suspend <hostname>  # remotely sends a host to suspend-to-ram

  Buildin help system:

   bar help [topic]
   ./bar help [topic]


INVOCATION AND SEMANTICS

   bar [rulefile] [--bare] [rule [arguments..]]
   please [rulefile] [--bare] [rule [arguments..]]
   ./bar [rulefile] [--bare] [rule [arguments..]]
   <symlink> [arguments..]

  Starts by loading all initial modules (those which have underscores in their name) and the
  rulefile, which is either "Barf", "barf", ".Barf", ".barf" when called as 'bar' or "Pleasef"
  "pleasef" ".Pleasef" ".pleasef" "\$HOME/.Pleasef" when called as 'please' and when the first
  argument is not a file.

  The duality of having 'bar' installed as 'please' is not only for making it more
  polite. This allows for a user to have private '.Pleasef' defining rules that are for common
  administration tasks distinct from versioned per-project 'Barf' and 'Bar.d' rules.

  Note that the rules for looking up the Barf/Pleasef and the modules are somewhat distinct.
  Nevertheless modules are in either way only loaded from a single directory and are not
  located in different paths. This is a opinionated choice to make the module system
  self-contained and not depend on secondary locations.

  Then the given rule (or MAIN) with the supplied arguments becomes evaluated. Finally, if
  a 'CLEANUP' rule exists, it is evaluated.

  The exit code of the invocation is the exit code of the main rule.

  Just calling 'bar' without any arguments will evaluate the 'MAIN' rule which should be what
  people expect by default. Other useful rules like 'help' for this documentation are defined
  by modules.

  When called by a symlink, the standard rulefile is loaded and instead of ‘MAIN’, a rule with
  the same name as the symlink is called with all arguments passed.


MODULE API/RULES

$(help_describe_files "$BAR_DIR"/* )


INITIAL INSTALLATION

  Bar can be invoked in different ways:

  1.  Installed in \$PATH:
      To make this work it is best to clone bar locally and symlink the checked out files
      to your '.local/' tree. This allows easy upgrades via git:

      When you have radicle (https://radicle.xyz/) installed you can clone it with:

       rad clone rad:z3WhBdHt1VVNyeQ61zpY66pNzuSrP

      Otherwise it can be cloned by git with:

       git clone https://seed.pipapo.org/z3WhBdHt1VVNyeQ61zpY66pNzuSrP.git bar

      Then you can install it in your ~/.local tree with:

       cd bar
       ./bar init_install ~/.local/

      This creates symlinks to 'bar', 'please', 'Bar.d', 'Barf.default', 'Please.default' in ~/.local
      and symlinks 'Bar.d/*' to '~/.config/please/'.

      Now 'bar' is installed, check it with 'bar help'

  2.  The local './bar' initialized from above:
      Since bar is a bash script, it’s easy to version and ship it with other software.
      To initialize it in a current directory use either of:

       bar init          # creates bar, Barf, Bar.d/
       bar init --hidden # creates .bar, .Barf, .Bar.d/

      After that Barf can be customized, unnecessary modules in Bar.d/ may be deleted.
      Once that is done these files should be put under version control.

      When the installed bar from 1. becomes updated then a local version can be updated by:

       bar init --update

      This only updates 'bar' and any existing modules in 'Bar.d/' but will not touch the
      'Barf' file since that is meant for local customization.

       bar init_update_merge_barf

      Will do a merge of the installed 'Barf' file with the local one. This *will* leave 3-way
      conflict markers behind when there are changes. These must be manually resolved!

      The updated files should then be committed to version control.

  3.  githooks symlinked from './.git/hooks/*' -> '../../bar'
      'bar' has support to be used as githooks. This needs manual enabling. Individual hooks can be
      enabled or disabled with 'bar githook_enable <hook>' and 'bar githook_disable <hook>'.
      For existing projects using 'bar' a maintainer can setup rules to activate all necessary hooks.
      This then can be activated by './bar activate'.


GIT HOOK ACTIVATION

  Bar will be inert in a project that ships with bar initialized. One can call it manually by
  './bar'.  A maintainer of the project may define 'activate' rules that activate
  githooks. These are then activated by './bar activate'. This will create symlinks in the
  '.git/hooks/' directory to the 'bar' script. These hooks will then be executed when the
  respective git hook is triggered. The rules for these hooks are defined in the 'Barf' file
  in the project directory.


RULE SEMANTICS

  Rules are a named, ordered collection of clauses. They are considered pure with inputs being
  the current directory name and the rule's arguments. Note that the content of files is *not*
  considered and the outcome of the rule should not depend on external variables. Rules are
  evaluated lazily, only once; the result of a rule is cached. This means that rules, esp. the
  actions within the body must have deterministic sematics. For performance reasons this is
  not enforced but one may observe surprising behavior when this requirement is violated.

  Rules will be autoloaded on demand from modules in 'Bar.d/' (see below AUTOMATIC MODULE
  LOADING). For rules where this fails a fallback exits that creates an implicit rule for any
  command and shell function defined with a body calling the respective command.

  Each clause in a rule has its own set of dependencies. Dependencies are other rules which
  are evaluated in order. When a (normal) dependency fails then rule it is considered to be
  failed as well and no further attempts to evaluate following dependencies and clauses are
  made.

  Dependencies can be used as 'checking' dependency which either expects the dependency to
  succeed (suffixed with a '?') or fail (prefixed with a '!'). When such a checking dependency
  fails then the rest of the current clause is skipped. This allows conditional evaluation.
  Further dependencies may be tagged as unconditional by suffix them when a tilde '~', these
  are just evaluated but rules evaluation will proceed unconditionally even if such a
  dependency fails.

  Finally every clause can have an optional body. This are shell commands executed when all
  dependencies succeeded. Because of quotiung in shell becomes a but unwieldly there are
  shortcuts to make the body refer to shell functions, this should be preferred.


RULE DEFINITION SYNTAX

   rule [[--rule-flag].. <name>:] [--clause-flag].. [[!]deps[?|~][??] args..]..
   rule [[--rule-flag].. <name>:] [--clause-flag].. [[!]deps[?|~][??] args..].. -
   rule [[--rule-flag].. <name>:] [--clause-flag].. [[!]deps[?|~][??] args..].. -- [body..]

  * [--rule-flag]

    Sets flags for a rule. Flags are additive and affect the rule, not single clauses.

    --always
      The result is not cached and the rule will be always evaluated again.

    --bare
      When this rule is called as initial rule (bar <rule>) then do not eval SETUP,
      PREPROCESS, POSTPROCESS and CLEANUP.

    --reverse
      The clauses of this rule will be evaluated in reverse order

    --disjunct
      Makes the clauses of this rule disjunctive. The rule will succeed with the first
      successful clause. Normally clauses are conjunctive and fail with the first failing
      clause.

    --meta
      Metarules do not have their own clause local variable. This allow them to modify
      the clause locals of the calling rule. 'clause_local' for example is a metarule.
      User defined rules that want to modify clause locals will need to be meta too.
      See 'try_cargo_toolchain' for an example.

  * [<name>:]

    A rule can have a optional name (suffixed with a colon).  When the name is not given it
    defaults to 'MAIN'.  Rules that have only a name but no dependencies and no body create a
    body that calls a bash command or function with the same name as the rule passing rule
    arguments to it.

  * [--clause-flag]..

    Sets flags affecting this clause only.

    --conclusive
      Makes a clause result conclusive, if not skipped no more clauses will be tried.

    --default
      Default clauses will be kept at the end of the list of clauses. Using '--default'
      together with 'disjunct' rules allows one to hook up action while maintaining a fallback
      or warning/error when no hooked up rule succeeded.

  * [[!]deps[?|~][??] args..]..

    Dependencies, are a list of other rules that this rule depends on. These will be executed
    in order. If any of the dependencies fails then this rule is considered failed as well, no
    further dependencies, bodies or clauses are executed unless this dependency is a checking
    or unconditional one.

    A dependency can be either prefixed with an exclamation mark or suffixed with question
    marks or a tilde. The exclamation mark prefix expects the dependency to fail and will
    continue then, if the dependency succeeds then the remaining dependencies and the rule
    body are skipped. With a question mark as suffix the dependency is expected to succeed,
    when it fails then the rest of the dependencies and the rule body is skipped. With a tilde
    as suffix outcome of the dependencny is ignored and the rest of the dependencies and the
    rule body is executed.  The difference here is that these checking dependencies decide if
    a clause should be skipped or succeed while a failure on a normal dependency will fail a
    rule instantly. When a rule is suffixed with two question marks then this behaves like
    "'rule_exists? dep' dep". Making this dependency optional. This can be combined with the
    another question mark, a tilde, or explamation mark prefix. This is commonly used to
    define optional rule hooks.

    Dependencies can have arguments. When provided then the dependency and its arguments must
    be quoted. These arguments are passed in the 'RULE_ARGS' array to the body of the rule.

  * -

    When there is a single hypen '-' at the end of a rule definition then the rule body is a
    call to a command or function of the same name as the rule with all arguments passed. This
    is used when one wants to add dependencies to a existing command or function.

  * -- [body..]

    After a double hyphen a optional rule body follows. This are the commands to
    execute for this clause. If these fail then the rule is considered failed. When a name but
    no body and no dependencies are given then the body defaults to the rule name. This makes
    it easy to translate simple parameterless commands and functions to rules. Usually the
    body has to be quoted to prevent shell expansions at definition time. Later when a rule
    becomes evaluated the body is passed to 'eval'.

    When the body is omitted, then the rule body is read from stdin. This allows to use
    heredocs or herestrings or read the body from a file.

    When a rule overrides an existing command a 'NOTE' will be printed on higher verbosity
    levels. The user is responsible for sensible overiding of commands.

  Rules must not have mutually recursive dependencies. When such is detected the
  evaluation aborts.

  Examples:

   # Add a clause to 'MAIN'
   rule -- echo hello

   # Different ways to define rule bodies
   rule foo_ok: -- echo inline
   rule foo_ok: -- '
       echo inline quoted
   '
   rule foo_ok: -- <<<"echo herestring"
   rule foo_ok: -- <<EOR
      echo heredoc
   EOR

   # Make a rule that fails
   rule foo_fail: -- false

   # functions and commands can be used as rules, this should be preferred
   function example
   {
       echo "i am example called with \$*"
   }

   # add a tests rule with 3 clauses
   rule tests: foo_ok? 'example "argument"' -- echo "foo_ok success"
   rule tests: !foo_ok -- echo "This is never called, but MAIN still passes"
   rule tests: foo_fail? -- echo "This is also never called"

   # add tests to MAIN
   rule tests

  For some more examples see the 'example' file that ships with bar.


  Special Rules and Names

    Rules that do not have a name fall back to 'MAIN', when no rule name is given at execution
    time then 'MAIN' will be evaluated.

    If exist 'SETUP', 'PREPROCESS', 'POSTPROCESS' and 'CLEANUP' will be called.
    * SETUP
      Should set up the environment for all subsequent evaluation. Rules in 'SETUP'
      should be self-sufficient and not expect a working environment yet.
      A failure here will abort bar.
    * PREPROCESS
      Doing any preparatory tasks within the set up environment.
      A failure here will abort bar.
    * MAIN
      When the bar is not called via a symlink or the user did not provide a rule to
      evaluate, then MAIN is the default rule. Otherwise the user supplied or symlink-deduced
      rulename will be evaluated. The result of this rule determines the exitcode of bar.
    * POSTPROCESS
      Is for evaluating things after the main rule finished. The environment and
      state is still the same as in the main rule. A failure here will be reported but not
      reflected in the exitode.
    * CLEANUP
      Is for removing temporary resources and doing any other kind of cleanup work. This
      means the state and environment at cleanup time may be differen/partially destructed and
      should not be relied upon. Clauses in the CLEANUP rule are evaluated in reverse order of
      their definition. A failure here will be reported but not reflected in the exitcode.

    After a rule that is not flagged with '--always' got evaluated it is not allowed to add
    more clauses to it anymore, as the outcome would be unexpected and impure.


  Keep-Going Mode

    Bar supports a keep-going facility via the BAR_KEEP_GOING environment variable. When
    enabled, clauses that fail do not immediately halt rule evaluation—subsequent clauses
    continue to execute, though the overall failure is still propagated.

    BAR_KEEP_GOING can be set to a number which is decremented on each failure, when this
    reachs zero no more failures are accepted and the evaluation will terminate.

    When BAR_KEEP_GOING set to anything else than a number then evaluation will accept
    infinite failures.

    When not set then it defaults to one then evaluation will terminate on the
    first failure.

    Clauses marked '--conclusive' immediately halt keep-going.


  Purity Requirements

    All rules and functions must be sequentiually pure in their success branch. This means
    side effects must not alter the behavior of subsequent rules when they fail. For rules
    where this may be the case, like rules changing directories they must rather die than
    proceed with a undefined state in case of a failure.


RULE ENVIRONMENT

  Rules implicitly depend on the arguments passed and the current directory they run in. Any
  other state or environment variable is not considered. When the result of a rule would
  depend on such external state then the rule is impure and may lead to wrong
  results.


MODULES

  Modules are shell snippets normally located in '\$BAR_DIR' ('Bar.d/', 'bar.d/', '.Bar.d/' or
  '.bar.d/') when called as 'bar' or symlink or '~/.config/please' when called as 'please'.
  The 'std_lib' and 'rules_lib' are always loaded at startup. Modules matching '*_rules' are
  also autoloaded at startup. Any other '*_lib' must be manuallly loaded with 'require'.
  Modules with simple alphabetic names without underscores are lazy loaded on demand.

  Modules are loaded with the 'require' function. This ensures that they are loaded only once.
  Require will load modules outside of '\$BAR_DIR' when a path containing at least one slash
  is given.

  The first variant for modules that are initially loaded is used for modules that define
  helper functions that don't have associated rules or rules that are primarly used for
  checking conditions before delegating to the actual rules which do the work.

  The second variant is for mudules that define rules which are self-contained and can't
  extend existing rules with new clauses. Here are the rules and functions which do the actual
  work.

  The reason for this is that some will add clauses to existing rule which must be done before
  the rules are evaluated while we can improve performance by lazy loading modules that are
  not always needed.

  The module loader derives the module name from the rule name by removing any prefixes and
  suffixes. Thus the rules which shall trigger loading must follow the naming schema with the
  module name after the prefixes in the rule name.

  Per convention '<name>_rules' is a module that contains the rules (and few functions) that
  that add clauses to other rules to make 'name' accessible. These '*_rules' files are
  autoloaded at startup.

  '<name>_lib' are libraries for support functions other modules may use (with 'require
  name_lib').


AUTOMATIC MODULE LOADING

  Rule names may include underscores, then the word before the first underscore is used to
  determine a module name used for auto-loading rules. They can have special prefixes which
  are removed when auto-loading:

  - 'is_', 'has_' and 'try_' are reserved for check rules they don't have any special
    semantic except for being stripped at auto loading.

  When a rule is not found then a module name is derived from the rule name by removing the
  'try_', 'is_', 'has_' prefixes and cutting off anything behind the first
  underscore. Eg. 'try_module_check' results in 'module'. This is then searched as
  'Bar.d/module', 'bar.d/module', '.Bar.d/module' or '.bar.d/module' (or respective please
  variants) and loaded if present. Thus modules that are automatically loaded must be named by
  single word without underscores.


STANDARD RULES

  Bar ships with a module that defines a set of standard rules where other modules can add
  clauses to. Check 'Bar.d/std_rules' for details.

  'SETUP', 'PREPROCESS', 'MAIN', 'POSTPROCESS' and 'CLEANUP' are special rule names called
  approbiately.

  The 'clause_local [var[=value]]' is for defining variables that are local to a clause.  Only
  scalars can be clause local. Ideally this should be used as dependency and setting a a
  variable to a value. It can be used in a function as well esp when creating other metarules.


MAIN API

$(help_describe_files "$BAR_SELF")


DOCUMENTATION WRITING GUIDELINES

  Bar uses a structured documentation format that serves both human readers and automated
  tools like help generation and bash completion. Documentation uses '##' comment markers.

  File-Level Documentation:

    Use '###' at the start of a file to describe the module/file:

     ### This module provides cargo/rust support.

  Variable Documentation:

    Variables declared with 'declare' can be documented on the same line:

     declare -g MYVAR="value" ## Description of the variable

  Function Documentation:

    Functions should have documentation in the form:

     function name ## [--opt] <required> [optional..] - Short description

    The parameter list uses a formal syntax:
    - <param>    - Mandatory parameter (prototype)
    - [param]    - Optional parameter (prototype)
    - <param..>  - One or more occurrences (suffix .. after closing >)
    - <param>..  - One or more occurrences (suffix .. after closing >)
    - [param..]  - Zero or more occurrences (suffix .. after closing ])
    - [param]..  - Zero or more occurrences (suffix .. after closing ])
    - <> and []  - Can be nested
    - word       - Anything not in <> or [] is a literal (like 'as', 'into', ':')
    - --flag     - Literal flag (can be in <--flag> for prototype completion)
    - -f         - Literal short flag
    - a|b        - Alternatives where a and b can be any of the above
                   (a|b|c|d etc. any number allowed)
                   Note: <a..|b> is at least one 'a' or a single 'b'
                         <a|b>.. is at least one of 'a' or 'b'
    - param      - Parameter names serve as prototypes for completion

    Examples:

    - function rename ## <this> as|into <that> - rename this as/into that
      Requires literal 'as' or 'into' at the 2nd position.
    - function process ## <input:> <output> - process input to output
      The colon ':' after <input> is a literal character.

    Parameter identifiers start with an alphabetic character followed by [[:alnum:]-_].
    These serve as prototypes for completion and are refined in following documentation.

    Multi-line documentation continues on following lines starting with '##':

     function foo ## [--verbose|-v] <input> [output] - Process files
     {
         ## [--verbose|-v] - Enable verbose output
         ## <input>         - Input file to process
         ## [output]        - Optional output file (defaults to stdout)
         ...
     }

  Rule Documentation:

    Rules are documented with '##' lines before the rule definition:

     ## <target> - Build the specified target
     rule build:

    For rules with parameters, use the same formal syntax as functions:

     ## [--toolchain] <target> [options..] - Build target
     rule build:

  Documentation Prototypes for Completion:

    Parameter identifiers map to completion functions. Common prototypes include:

    - <file>      - Any file on filesystem
    - <directory> - Any directory
    - <path>      - Any valid path
    - <text>      - Any text input
    - <number>    - Numeric input
    - <rule>      - Existing rule name
    - <command>   - Command or function name

    Module-specific prototypes can be defined (e.g., <toolchain> in cargo module).
    See contrib/bar_complete for completion implementation details.
    
  Defining Custom Completion Prototypes:

    Modules can define custom prototypes for parameter completion using single-hash comments
    that must start at column 0 (no leading whitespace):
    
      # prototype: "mytype" = "file"
      # prototype: "myfile" = "file existing local"
      # prototype: "mycommand" = "command"
      # prototype: "toolchain" = "extcomp cargo"
      # prototype: "gitargs" = "extcomp git"
    
    These definitions register a prototype with a completer. The format is:

      # prototype: "prototype_name" = "completer_spec"
    
    Where completer_spec is either:
    - A built-in completer name (file, directory, path, rule, command, etc.)
    - A completer with predicates (e.g., "file existing local")
    - "ext function_name" for external/custom completers (calls bar --bare function_name)
    - "extcomp command" for black-box external command completion (invokes command's native bash completion)
    
    The "extcomp" type enables leveraging any command's existing bash completion by invoking
    it as a black box. For example, "extcomp git" will use git's native completion for all
    git subcommands and flags. This works with git, cargo, ssh, and any other command that
    has bash completion support.
    
    Note: The '# prototype:' comment must start at the beginning of the line (column 0).
    
    These are registered as "module@prototype" in the completion registry, allowing
    module-specific completion behavior while maintaining fallback to global prototypes.


BASH COMPLETION

  Bar supports bash completion for rulefiles, rules, functions, and their arguments. Completion
  is automatically installed when you run 'bar init_install'.

  The completion script is installed to '~/.bash_completion/bar_complete'. To enable it,
  either source it in your .bashrc:

   source ~/.bash_completion/bar_complete

  Or if you have bash-completion package installed, it should be automatically loaded.

  Completion works for:

  - bar <TAB>       - completes rulefiles, rules, and functions in current directory
  - please <TAB>    - completes rulefiles, rules, and functions
  - ./bar <TAB>     - completes rulefiles, rules, and functions from local bar

  The completion logic will:

  1.  Find any user rule files in current directory (files containing 'function' or 'rule',
      or with shebang pointing to bar/please)
  2.  Complete available bash functions and rules from default rule file and Bar.d/ modules
  3.  Provide context-aware argument completion based on parameter types


LICENSE

    bar -- BAsh Rulez
    Copyright (C) 2025  Christian Thäter <ct.bar@pipapo.org>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.
EOF
  fi

  if [[ -z "$span" ]]; then
    printf '%s\n' "${help_render_cache[@]}"
    return
  fi

  if [[ "$span" =~ ^([0-9]+)-([0-9]+)$ ]]; then
    local start="${BASH_REMATCH[1]}"
    local end="${BASH_REMATCH[2]}"
    local i
    for ((i=start; i<=end; i++)); do
      printf '%s\n' "${help_render_cache[i-1]}"
    done
    return
  fi

  printf '%s\n' "${help_render_cache[@]}"
}


function help_indexer
{
  help_render | awk '
    function trim(str) {
      gsub(/^[ \t]+|[ \t]+$/, "", str)
      return str
    }

    function record_result(start, end, proto, value,    idx) {
      if (end < start) {
        end = start
      }
      idx = ++result_count
      result_start[idx] = start
      result_end[idx] = end
      result_proto[idx] = proto
      result_value[idx] = value
    }

    function close_sections(new_indent,    end_line) {
      while (stack_size > 0 && stack_indent[stack_size] >= new_indent) {
        end_line = stack_last_content[stack_size]
        if (end_line == 0) {
          end_line = stack_start[stack_size]
        }
        record_result(stack_start[stack_size], end_line, stack_proto[stack_size], stack_value[stack_size])
        stack_size--
      }
    }

    function push_section(proto, value, indent) {
      stack_size++
      stack_indent[stack_size] = indent
      stack_proto[stack_size] = proto
      stack_value[stack_size] = value
      stack_start[stack_size] = NR
      stack_last_content[stack_size] = NR
    }

    function touch_sections() {
      for (i = 1; i <= stack_size; i++) {
        stack_last_content[i] = NR
      }
    }

    function find_span_end(start, start_indent,    j, end_line) {
      end_line = start
      for (j = start + 1; j <= NR; j++) {
        if (line_has_text[j] == 0) {
          continue
        }
        if (indentation[j] <= start_indent) {
          break
        }
        end_line = j
      }
      return end_line
    }

    BEGIN {
      code_indent = 0
      stack_size = 0
      result_count = 0
    }

    {
      line = $0
      indent = 0
      if (match(line, /^ +/)) {
        indent = RLENGTH
      }

      trimmed = trim(line)
      has_text = (trimmed != "") ? 1 : 0

      if (code_indent > 0) {
        if (trimmed != "" && indent < code_indent) {
          code_indent = 0
        } else {
          trimmed_lines[NR] = ""
          blank[NR] = 1
          indentation[NR] = indent
          line_has_text[NR] = has_text
          if (has_text) {
            close_sections(indent)
            touch_sections()
          }
          next
        }
      }

      if (trimmed != "" && (indent % 2) == 1) {
        code_indent = indent
        trimmed_lines[NR] = ""
        blank[NR] = 1
        indentation[NR] = indent
        line_has_text[NR] = has_text
        if (has_text) {
          close_sections(indent)
          touch_sections()
        }
        next
      }

      trimmed_lines[NR] = trimmed
      blank[NR] = (trimmed == "") ? 1 : 0
      indentation[NR] = indent
      line_has_text[NR] = has_text

      if (has_text) {
        close_sections(indent)
      }

      if (line ~ /^    Functions:/) {
        section = "function"
        if (has_text) {
          touch_sections()
        }
        next
      }
      if (line ~ /^    Rules:/) {
        section = "rule"
        if (has_text) {
          touch_sections()
        }
        next
      }
      if (line ~ /^    Variables:/) {
        section = "variable"
        if (has_text) {
          touch_sections()
        }
        next
      }

      if (section != "" && line ~ /^      [^[:space:]]/) {
        name = trimmed
        split(name, parts, /[[:space:]]+/)
        name = parts[1]
        sub(/:$/, "", name)
        push_section(section, name, indent)
      }

      if (has_text && line !~ /^      / && line !~ /^        / && line !~ /^    (Functions|Rules|Variables):/) {
        section = ""
      }

      if (has_text) {
        touch_sections()
      }
    }

    END {
      close_sections(-1)
      for (i = 1; i <= NR; i++) {
        candidate = trimmed_lines[i]
        if (candidate == "") {
          continue
        }
        if (candidate ~ /^[[:punct:]]/ || candidate ~ /[[:punct:]]$/) {
          continue
        }
        if (candidate ~ / - /) {
          continue
        }
        prev_blank = (i == 1) ? 1 : blank[i - 1]
        next_blank = (i == NR) ? 0 : blank[i + 1]
        if (prev_blank && next_blank) {
          span_end = find_span_end(i, indentation[i])
          record_result(i, span_end, "topic", candidate)
        }
      }

      for (i = 1; i <= result_count; i++) {
        printf "%d-%d:%s:%s\n", result_start[i], result_end[i], result_proto[i], result_value[i]
      }
    }
  '
}


function help_describe_files
{
    local file
    for file in "$@"; do
        if help_describe_file "$file"; then
            help_describe_variables "$file"
            help_describe_functions "$file"
            help_describe_rules "$file"
        else
            warn "$file has no top level doc"
        fi
    done
}


function help_describe_file
{
    awk '
        function printout(text) {
            out = out text "\n"
        }

        /^###/ {
            line = $0
            sub(/^###[ ]?/, "", line)
            printout(indent line)
            indent = "    "
            next
        }

        END {
            name = FILENAME
            gsub(/^.*\//, "", name)
            if (out != "") {
                print "  " name " - " out
            } else {
                exit 1
            }
        }
    ' "$1"
}

function help_describe_functions
{
    awk '
        function printout(text) {
            out = out text "\n"
        }

    /^function[ \t]+[A-Za-z_][A-Za-z0-9_]*[ \t]*##/ {
            split($0, parts, "##")
            if (length(parts) < 2) {
                next
            }

            namepart = parts[1]
      sub(/^function[ \t]+/, "", namepart)
            sub(/[ \t].*$/, "", namepart)

            infopart = parts[2]
            sub(/^[ \t]+/, "", infopart)

            proto = infopart
            desc = ""
            split(infopart, proto_desc, " - ")
            if (length(proto_desc) >= 2) {
                proto = proto_desc[1]
                desc = substr(infopart, length(proto) + 4)
            }

            if (proto == infopart) {
                desc = ""
            }

            printout()
            if (proto != "") {
                printout("      " namepart " " proto)
            } else {
                printout("      " namepart)
            }
      if (desc != "") {
                printout("        " desc)
            }
            next
        }

        /^([ \t][ \t])+##[^#].*/ {
            line = $0
            sub(/^.*##[ ]?/, "", line)
            printout("        " line)
            next
        }

        END {
            if (out != "") {
                print "    Functions:"
                print out
            }
        }
    ' "$1"
}

function help_describe_rules
{
    awk '
        function printout(text) {
            out = out text "\n"
        }

    function trim(text) {
      sub(/^[ \t]+/, "", text)
      sub(/[ \t]+$/, "", text)
      return text
    }

    function reset_docs(    idx) {
      doc_count = 0
      for (idx in doc_lines) {
        delete doc_lines[idx]
      }
    }

    BEGIN {
      doc_count = 0
    }

    /^rule([ \t].*)?/ {
      if (doc_count > 0) {
        line = $0
        sub(/^.*rule[ \t]+/, "", line)
        while (line ~ /^--[A-Za-z_-]+[ \t]+/) {
          sub(/^--[A-Za-z_-]+[ \t]+/, "", line)
        }
        rule_name = line
        sub(/[ \t].*$/, "", rule_name)
        sub(/:$/, "", rule_name)

        first = trim(doc_lines[1])
        proto_line = ""
        summary = ""
        split_pos = index(first, " - ")
        if (split_pos > 0) {
          proto_line = trim(substr(first, 1, split_pos - 1))
          summary = trim(substr(first, split_pos + 3))
        } else {
          summary = first
        }

        printout("")
        if (proto_line != "") {
          printout("      " rule_name " " proto_line)
        } else {
          printout("      " rule_name)
        }
        if (summary != "") {
          printout("        " summary)
        }

        if (doc_count > 1) {
          for (i = 2; i <= doc_count; i++) {
            extra = trim(doc_lines[i])
            if (extra != "") {
              printout("        " extra)
            }
          }
        }
      }

      reset_docs()
      next
    }

    /^##[^.]/ {
      line = $0
      sub(/^##[ \t]*/, "", line)
      doc_count++
      doc_lines[doc_count] = line
      next
    }

    {
      reset_docs()
      next
    }

    END {
      if (out != "") {
        print "    Rules:"
        print out
      }
    }
  ' "$1"
}



function help_describe_variables
{
    awk '
        function printout(text) {
            out = out text "\n"
        }

    /declare[ \t]+.*##/ {
      before = $0
      sub(/[ \t]*##.*/, "", before)
      desc = $0
      sub(/^.*##[ ]?/, "", desc)

      rest = before
      sub(/^declare[ \t]+/, "", rest)

      flags = ""
      if (rest ~ /^-[A-Za-zA-Z]+/) {
        flags = rest
        sub(/[ \t].*$/, "", flags)
        sub(/^-/, "", flags)
        sub(/^[^ \t]+[ \t]*/, "", rest)
      }

      varname = rest
      sub(/[ \t=].*$/, "", varname)

      if (varname == "") {
        next
      }

      value = rest
      if (value ~ /=/) {
        equals = index(value, "=")
        value = substr(value, equals + 1)
        sub(/^[ \t]*"?/, "", value)
        sub(/"?[ \t]*$/, "", value)
      } else {
        value = ""
      }

      line = "      " varname
      if (flags != "") {
        line = line " (" flags ")"
      }

      printout("")
      printout(line)
      printout("        " desc)
      if (value != "") {
        printout("        Default: " value)
      }
      next
    }

        END {
            if (out != "") {
                print "    Variables:"
                print out
            }
        }
    ' "$1"
}

# Define --bare rule for help (reads existing module files)
## [[-s|--short] topic|rule|function|variable|text] - Show help topics
##   - [-s|--short]:                 Show only the queried sections
##   - topic|rule|function|variable: Navigate to or show only specified topics
##   - text:                         Search the specified text in the documentation
rule --bare help:

# Provide indexer via bare rule for external consumers like completion
rule --bare help_indexer:

