#!/bin/zsh

### Remove a cloned bundle.
#
# usage: antidote purge [-h|--help] <bundle>
#        antidote purge [-a|--all]
#
#function antidote-purge {
  emulate -L zsh; setopt local_options $_adote_funcopts

  local o_help o_all
  zparseopts $_adote_zparopt_flags -- \
    h=o_help -help=h \
    a=o_all  -all=a  ||
    return 1

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

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

  local bundlefile
  zstyle -s ':antidote:bundle' file 'bundlefile' ||
    bundlefile=${ZDOTDIR:-$HOME}/.zsh_plugins.txt

  if (( $#o_all )); then
    # last chance to save the user from themselves
    local antidote_home="$(antidote-home)"
    local REPLY
    zstyle -s ':antidote:purge:all' answer 'REPLY' || {
      read -q "REPLY?You are about to permanently remove '$antidote_home' and all its contents!"$'\n'"Are you sure [Y/n]? "
      print
    }
    [[ ${REPLY:u} == "Y" ]] || return 1
    # remove antidote home and static cache file
    __antidote_del -rf -- "$antidote_home"

    if [[ -e "${bundlefile:r}.zsh" ]]; then
      zstyle -s ':antidote:purge:all' answer 'REPLY' || {
        read -q "REPLY?You are about to remove '${bundlefile:t:r}.zsh'"$'\n'"Are you sure [Y/n]? "
        print
      }
      if [[ ${REPLY:u} == "Y" ]]; then
        local dtstmp=$(date -u '+%Y%m%d_%H%M%S')
        command mv -f "${bundlefile:r}.zsh" "${bundlefile:r}.${dtstmp}.bak"
        print "'"${bundlefile:r}.zsh"' backed up to '${bundlefile:t:r}.${dtstmp}.bak'"
      fi
    fi
    print "Antidote purge complete. Be sure to start a new Zsh session."

  else
    local bundle=$1
    # make sure the user isn't trying to do something out-of-bounds
    if [[ -e "$bundle" ]]; then
      print -ru2 "antidote: error: '$bundle' is not a repo and cannot be removed by antidote."
      return 2
    fi

    local bundledir=$(__antidote_bundle_dir $bundle)
    if [[ ! -d "$bundledir" ]]; then
      print -ru2 "antidote: error: $bundle does not exist at the expected location: $bundledir"
      return 1
    fi

    # remove
    __antidote_del -rf "$bundledir"
    print "Removed '$bundle'."

    # attempt to comment out the bundle from .zsh_plugins.txt
    if [[ -e "$bundlefile" ]]; then
      local tmpfile="${bundlefile}.antidote.tmp"
      $__adote_awkcmd -v pat="$bundle" '$0~"^[[:blank:]]*"pat{print "# " $0;next}1' <$bundlefile >|$tmpfile
      command mv -f "$tmpfile" "$bundlefile" || __antidote_del -f "$tmpfile"
      print "Bundle '$bundle' was commented out in '$bundlefile'."
    fi
  fi
#}
