#!/bin/zsh

### Setup antidote.
#function antidote-setup {
  0=${(%):-%x}
  typeset -gH ANTIDOTE_ZSH="${0:a:h:h}/antidote.zsh"

  typeset -gU fpath
  fpath=( "${0:a:h}" $fpath )
  local fn
  for fn in ${0:a:h}/*; do
    [[ ${fn:t} != 'antidote-setup' ]] || continue
    if typeset -f ${fn:t} > /dev/null; then
      unfunction -- ${fn:t}
    fi

    # autoload extensionless function files
    [[ -z "${fn:e}" ]] && autoload -Uz "${fn}"
  done

  # man pages
  if [[ "$MANPATH" != *"${0:a:h:h}/man"* ]]; then
    export MANPATH="${0:a:h:h}/man:$MANPATH"
  fi

  # Only the subprocess sourced the config file, so parent-shell code
  # never saw its zstyles. Source it once, here.
  typeset -g ANTIDOTE_CONFIG=${ANTIDOTE_CONFIG:-${XDG_CONFIG_HOME:-$HOME/.config}/antidote/config.zsh}
  if [[ -r "$ANTIDOTE_CONFIG" ]]; then
    # The autoload route reaches this after the user's own zstyles, so
    # keep the config from overwriting them: it supplies defaults only.
    zstyle() {
      local -a _adote_set
      if [[ "$1" != -* ]] && (( $# >= 3 )) &&
         builtin zstyle -g _adote_set "$1" "$2"; then
        return 0
      fi
      builtin zstyle "$@"
    }
    builtin source "$ANTIDOTE_CONFIG"
    unfunction zstyle
  fi
  # Tells the subprocess the file was already tried, so it skips its own
  # source and takes the result from the zstyles handed across.
  builtin zstyle ':antidote:config' sourced 'yes'

  builtin autoload -Uz is-at-least
  if is-at-least 5.8; then
    # -D : Delete flags from the param array once they are detected
    # -M : Map a flag to alternative names (useful for defining -s(hort) and --long options)
    # -F : Fail if a flag is provided that was not defined in the zparseopts spec
    # the -F option was added in 5.8
    typeset -gHa _adote_zparopt_flags=( -D -M -F )
  else
    typeset -gHa _adote_zparopt_flags=( -D -M )
  fi

#}
