#!/bin/zsh

### Update antidote and its cloned bundles.
#
# usage: antidote update [-h|--help]
#
#function antidote-update {
  0=${(%):-%x}
  emulate -L zsh; setopt local_options $_adote_funcopts

  local o_help o_self o_bundles
  zparseopts $_adote_zparopt_flags -- \
    h=o_help    -help=h    \
    s=o_self    -self=s    \
    b=o_bundles -bundles=b ||
    return 1

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

  # colors
  local green normal
  if [[ $TERM = *256color* || $TERM = *rxvt* ]]; then
    if (( $+commands[tput] )); then
      green=$(tput setaf 2)
      normal=$(tput sgr0)
    else
      green=$'\E[32m'
      normal=$'\E[0m'
    fi
  fi

  if (( $#o_bundles )) || ! (( $#o_self )); then
    print "Updating bundles..."
    local bundledir url repo

    # remove zcompiled files
    __antidote_del -rf -- $(antidote-home)/**/*.zwc(N)

    # remove check file
    local loadable_check_path="$(antidote-home)/.antidote.load"
    [[ -r "$loadable_check_path" ]] && __antidote_del -- "$loadable_check_path"

    # update all bundles
    for bundledir in $(antidote-list --dirs); do
      url=$(git -C "$bundledir" config remote.origin.url)
      repo="${url:h:t}/${${url:t}%.git}"
      print "antidote: checking for updates: $url"
      () {
        local oldsha=$(git -C "$1" rev-parse --short HEAD)
        git -C "$1" pull --quiet --ff --rebase --autostash
        git -C "$1" submodule --quiet sync --recursive
        git -C "$1" submodule --quiet update --init --recursive --depth 1
        local newsha=$(git -C "$1" rev-parse --short HEAD)
        if [[ $oldsha != $newsha ]]; then
          print "${green}antidote: updated: $2 ${oldsha} -> ${newsha}${normal}"
          git -C "$1" --no-pager log --oneline --ancestry-path ${oldsha}..${newsha} 2>/dev/null
        fi

        # recompile bundles
        if zstyle -t ":antidote:bundle:$repo" zcompile; then
          __antidote_bundle_zcompile $bundledir
        fi
      } "$bundledir" "$url" &
    done
    print "Waiting for bundle updates to complete..."
    print ""
    wait
    print "${green}Bundle updates complete.${normal}"
    print ""
  fi

  # update antidote
  if (( $#o_self )) || ! (( $#o_bundles )); then
    print "Updating antidote..."
    if [[ -d "${0:A:h:h}/.git" ]]; then
      git -C "${0:A:h:h}" pull --quiet --ff --rebase --autostash
      print "antidote self-update complete.\n"

      # setup antidote again
      (( $+functions[__antidote_setup] )) && unfunction __antidote_setup
      builtin autoload -Uz ${0:A:h}/__antidote_setup
      __antidote_setup

      # show antidote version
      antidote -v
    else
      print "Self updating is disabled in this build."
      print "Use your OS package manager to update antidote itself."
    fi
  fi
#}
