# Tools
alias g="git"

y() {
  local unignore="$XDG_CONFIG_HOME/yadm/unignore"
  test -r "$unignore" && cat "$unignore" | while read f; do eval ls -d $f; done | yadm add --intent-to-add --pathspec-from-file=-
  test "$#" -eq 0 && yadm s || yadm "$@"
}
yc() {
  local folder="$(test -e "${1:-$PWD}" && realpath "${1:-$PWD}" || echo "$XDG_CONFIG_HOME/$1")"
  echo "${folder#$HOME\/.}:" >/tmp/yc-msg
  yadm commit -v --template /tmp/yc-msg ${@:2} -- "$folder*"
}

gcn() {
  local root="$(git rev-parse --show-toplevel)"
  if test "$root" = "$DATA"
  then
    if test $# -eq 0 || test -e "$1"
    then
      fulldir="$(realpath ${1:-$PWD})"
      dir="${fulldir#$root/?-}"
    else
      dir="box/$1"
      fulldir="$root/2-$dir"
    fi
  else
      fulldir="$(realpath ${1:-$PWD})"
      dir="${fulldir#$root/}"
  fi
  echo "$dir: " >/tmp/gcn-msg
  git add $fulldir
  git moves -q
  git commit -v --template /tmp/gcn-msg ${@:2} #-- $fulldir
}

# if in home or under XDG_CONFIG_HOME and not within a git directory, replace git by yadm
git() {
  case "$1" in
    (reset) test "$2" = "--hard" && return 66;;
    (config) ;;
    (clone) ;;
    (*) case "$PWD" in
      ($HOME|$XDG_CONFIG_HOME|$LAST_YADM)
        yadm "$@"
        return $?
        ;;
      ($XDG_CONFIG_HOME*|$HOME/.local*)
        if ! command git rev-parse --show-toplevel &>/dev/null; then
          export LAST_YADM="$PWD"
          yadm "$@"
          return $?
        fi;;
    esac;;
  esac
  command git "$@"
}

# BRANCHES
# Remove list of tags local & remote
gitrmtag() {
  declare -a refs
  local index=1
  for tag in $@; do refs[index++]=":refs/tags/$tag"; done
  git push origin "${refs[@]}" && git tag -d "$@"
}
# Rename a tag
gitretag() {
  git push origin refs/tags/${1}:refs/tags/${2} :refs/tags/$1 && git tag -d $1
}

# Testing
gittestcommit() { touch file$((++i)) && git add 'file*' && git commit -m "Create file$i"; }