#!/bin/zsh

### Clone bundle(s) and generate the static load script.
#
# usage: antidote bundle [-h|--help] <bundle>...
#

### Clone bundle(s) and generate the static load script.
#function antidote-bundle {
  # Download a bundle and prints its Zsh source line.
  emulate -L zsh; setopt local_options $_adote_funcopts

  local o_help
  zparseopts $_adote_zparopt_flags -- h=o_help -help=h || return 1

  if (( $#o_help )); then
    antidote-help bundle
    return
  fi

  # handle bundles as newline delimited arg strings,
  # or as <redirected or piped| input
  local -a bundles=("${(@f)$(__antidote_collect_input "$@")}")
  (( $#bundles )) || return 1

  # output static file compilation
  local -a zcompile_script=(
    "function {"
    '  0=${(%):-%x}'
    '  local staticfile=${0:A}'
    '  [[ -e ${staticfile} ]] || return 1'
    '  if [[ ! -s ${staticfile}.zwc || ${staticfile} -nt ${staticfile}.zwc ]]; then'
    '    builtin autoload -Uz zrecompile'
    '    zrecompile -pq ${staticfile}'
    '  fi'
    '}'
  )
  if zstyle -t ':antidote:static' zcompile; then
    printf '%s\n' $zcompile_script
  fi

  # antidote-script also clones, but this way we can do it all at once in parallel!
  if (( $#bundles > 1 )); then
    source <(printf '%s\n' $bundles | __antidote_bulk_clone)
  fi

  # generate bundle script
  source <(printf '%s\n' $bundles | __antidote_parse_bundles) | __antidote_filter_defers
#}
