#!/usr/bin/env bash

VERSION="5.1.0"
INSTALL_SCRIPT="https://raw.githubusercontent.com/tj/git-extras/master/install.sh"

update() {
  local bin="$(which git-extras)"
  local prefix=${bin%/*/*}
  local orig=$PWD

  curl -s $INSTALL_SCRIPT | PREFIX="$prefix" bash /dev/stdin \
    && cd "$orig" \
    && echo "... updated git-extras $VERSION -> $(git extras --version)"
}

updateForWindows() {
  local bin="$(which git-extras)"
  local prefix=${bin%/*/*}
  local orig=$PWD
  
  # we need to clean up /tmp manually on windows
  cd /tmp \
    && rm -rf ./git-extras \
    && echo "Setting up 'git-extras'...." \
    && git clone https://github.com/tj/git-extras.git &> /dev/null \
    && cd git-extras \
	&& git checkout \
        $(git describe --tags $(git rev-list --tags --max-count=1)) \
        &> /dev/null \
	&& ./install.cmd "$prefix" \
	&& cd "$orig" \
	&& echo "... updated git-extras $VERSION -> $(git extras --version)"
  rm -rf /tmp/git-extras &> /dev/null
}

case "$1" in
  -v|--version)
    echo $VERSION && exit 0
    ;;
  update)
    platform=$(uname -s)
    if [ "${platform::9}" = "CYGWIN_NT" ] || \
      [ "${platform::5}" = "MINGW" ] || \
      [ "${platform::7}" = "MSYS_NT" ]
    then
      updateForWindows
    else
      update
    fi
    ;;
  *)
    git extras --help
    ;;
esac
