#!/usr/bin/env bash

git fetch &

MAIN_BRANCH="main"
# detect master / main branch
if [ "$(git rev-parse --quiet --verify $MAIN_BRANCH)" ]; then
  echo "main branch: ${MAIN_BRANCH}"
else
  MAIN_BRANCH="master"
  echo "main branch: ${MAIN_BRANCH}"
fi

GITROOT=`git rev-parse --show-toplevel`
YARN_CHANGE=""
if [[ -f "$GITROOT/yarn.lock" ]]; then
  if [ -n "$(git diff origin/$MAIN_BRANCH head yarn.lock)" ]; then 
    YARN_CHANGE="1"
  fi
fi

current_branch=$(git rev-parse --abbrev-ref HEAD)
if [ -n "$(git status --porcelain)" ]; then 
  if [ $current_branch == $MAIN_BRANCH ]; then
    function yes_or_no {
        while true; do
            read -p "$* [y/n]: " yn
            case $yn in
                [Yy]*) return 0  ;;  
                [Nn]*) echo "Aborted" ; return  1 ;;
            esac
        done
    }
    if [ -n "$(git status --porcelain)" ]; then 
      git st
      echo ""
      yes_or_no "💥 RESET GIT TO HEAD?" && git add --all && git reset --hard HEAD && echo "🧹 Clean" || exit 1
    else
      echo "🧹 Already clean"
    fi
  else
    echo '❌ branch not clean';
    exit 1;
  fi
fi

if [ $current_branch == $MAIN_BRANCH ]; then
  echo "pull"
else
  git checkout $MAIN_BRANCH || exit 1;
fi

wait

CLEANUP="1"
if [ "$(git pull)" == "Already up to date."  ]; then
  CLEANUP=""
fi

if [ -n "$CLEANUP" ]; then
# delete all merged branches
(
  (git for-each-ref refs/heads/ "--format=%(refname:short)" | while read branch; do mergeBase=$(git merge-base master $branch) && [[ $(git cherry master $(git commit-tree $(git rev-parse $branch\^{tree}) -p $mergeBase -m _)) == "-"* ]] && git branch -D $branch; done);
  (git prune && echo "pruned");
) &
else 
  echo "skip cleanup";
fi

if [ -n "$YARN_CHANGE" ]; then 
  (cd "$GITROOT"; yarn --immutable)
else
  echo "yarn.lock was unchanged"
fi

if [ -n "$CLEANUP" ]; then
  echo "🧹 cleaning up"
  wait
fi

echo "✨ done"