#!/usr/bin/env bash
#
# Changes Git branch and pulls remote changes (based on git-friendly's pull command).
#
# - Switch to or create a branch:
#
# `br {{branch}}`
#
# - Switch to a previous branch:
#
# `br -`
#
# - Delete a local fully merged branch:
#
# `br -d {{branch}}`
#
# - Delete a local not fully merged branch:
#
# `br -D {{branch}}`
#
# ---
#
# See more:
# https://github.com/jamiew/git-friendly
#
# Author: Artem Sapegin, sapegin.me
# License: MIT
# https://github.com/sapegin/dotfiles

# shellcheck disable=SC2250

# Common stuff
RED="$(tput setaf 1)"
UNDERLINE="$(tput sgr 0 1)"
NOCOLOR="$(tput sgr0)"
error() { printf '%b\n' "$UNDERLINE$RED$1$NOCOLOR"; }

# Check whether a local branch exists
has_local_branch() {
  name="$1"
  if git show-ref --quiet "refs/heads/$name"; then
    return 0
  else
    return 1
  fi
}

# Check whether a remote branch exists
has_remote_branch() {
  name="$1"
  if git ls-remote --exit-code --heads "$remote" "$name" >/dev/null 2>&1; then
    return 0
  else
    return 1
  fi
}

# Pull if has remote
try_pull() {
  if has_remote_branch "$branch"; then
    echo "Pull"
    pull
  fi
}

# Attempt to use master branch in repository where main is used
if [ "$branch" = "master" ]; then
  if has_local_branch "main"; then
    git switch main
    echo "This repository uses main branch, not master"
    try_pull
    exit 0
  fi
fi

# Attempt to use main branch in repository where master is used
if [ "$branch" = "main" ]; then
  if has_local_branch "master"; then
    git switch master
    echo "This repository uses master branch, not main"
    try_pull
    exit 0
  fi
fi

remote="origin"
branch="$1"
delete=
if [ "$1" = "-d" ] || [ "$1" = "-D" ]; then
  delete="$1"
  branch="$2"
fi

# Switch to the previous branch
if [ "$branch" = "-" ]; then
  git switch -
  branch=$(git rev-parse --abbrev-ref HEAD)
  try_pull
  exit 0
fi

# Delete branch
if [ -n "$delete" ]; then
  echo "💀 Removing local branch $branch..."
  git branch "$delete" "$branch"
  exit 0
fi

if has_local_branch "$branch"; then
  # Local branch already exists, switching
  echo "👓 Switching to existing local branch $branch..."
  git switch "$branch"
  if has_remote_branch "$branch"; then
    # Fix tracking if needed
    tracking=$(git branch -vv | grep "*" | awk '{ print $4 }')
    if [[ ! "$tracking" =~ "$remote" ]]; then
      echo "⚙️ Your local branch is not tracking the corresponding remote branch, fixing..."
      git branch --set-upstream-to "$branch" "$remote/$branch"
    fi

    # Pull
    pull
  fi
else
  # No local branch
  if has_remote_branch "$branch"; then
    # Remote branch exists, fetching and switching
    echo "🛸 Fetching remote branch $branch..."
    git fetch "$remote" "$branch"
    echo
    git switch -c "$branch" --track "$remote/$branch"
  else
    # No remote branch, creating a new branch
    echo "🪴 Creating new local branch $branch..."
    git checkout -b "$branch"
  fi
fi
