#!/bin/zsh

### Clone a new bundle and add it to your plugins file.

# usage: antidote install [-h|--help] [-k|--kind <kind>] [-p|--path <path>]
#                         [-c|--conditional <func>] [-b|--branch <branch>]
#                         [--pre <func>] [--post <func>]
#                         [-a|--autoload <path>] <bundle> [<bundlefile>]
#function antidote-install {
  emulate -L zsh; setopt local_options $_adote_funcopts

  local -A flag_to_annotation=(
    '-a' autoload
    '-b' branch
    '-c' conditional
    '-h' help
    '-k' kind
    '-p' path
  )
  local -a annotations=()
  local arg
  while (( $# )); do
    arg="$1"
    case "$arg" in
      -h|--help)
        antidote-help install
        return
      ;;
      --)   shift; break  ;;
      --*)  annotations+=( "${arg#*--}:$2" ); shift  ;;
      -*)   annotations+=( $flag_to_annotation[$arg]:$2 ); shift  ;;
      *)    break  ;;
    esac
    shift
  done

  if [[ $# -eq 0 ]]; then
    print -ru2 "antidote: error: required argument 'bundle' not provided, try --help"
    return 1
  fi

  local bundle=$1
  local bundlefile=$2
  if [[ -z "$bundlefile" ]]; then
    zstyle -s ':antidote:bundle' file 'bundlefile' ||
      bundlefile=${ZDOTDIR:-$HOME}/.zsh_plugins.txt
  fi

  local bundledir=$(__antidote_bundle_dir $bundle)
  if [[ -d "$bundledir" ]]; then
    print -ru2 "antidote: error: $bundle already installed: $bundledir"
    return 1
  fi

  # use antidote bundle to clone our bundle
  local bundlestr=$bundle
  (( $#annotations )) && bundlestr+=" $annotations"
  antidote-bundle "$bundlestr" >/dev/null
  if [[ $? -ne 0 ]]; then
    print -ru2 "antidote: unable to install bundle '$bundle'."
  else
    print "Adding bundle to '$bundlefile':"
    print $bundlestr | tee -a $bundlefile
  fi
#}
