#!/bin/sh
#
# push - simplified version of git-friendly push
#
# send your local branch changes to the remote branch,
# and copy the relevant github 'compare' url to your clipboard (mac/linux only)
#
# any extra args to this command will be passed through to 'git push',
# e.g. for doing "push -f"
#
# ---
# source: https://github.com/git-friendly/git-friendly

# abort if this isn't a git repository
git rev-parse --is-inside-work-tree >/dev/null || exit "$?"

# get parent branch
# see: https://overflow.adminforge.de/questions/17843908/placeholder
get_parent() {
  git show-branch | grep '*' \
    | grep -v "$(git rev-parse --abbrev-ref HEAD)" \
    | head -n 1 | sed 's/.*\[\(.*\)\].*/\1/' | sed 's/[\^~].*//'
}

# colors
# shellcheck disable=SC2312
# color_error="$(tput setaf 1)"
color_error="$(tput sgr 0 1)$(tput setaf 1)"
color_reset="$(tput sgr0)"

# TODO(2025-08-03): DRY this b/w pull and push
branch=$(git branch --no-color 2>/dev/null \
  | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/') || exit "$?"
default_remote="origin"
remote=$(git config "branch.${branch}.remote" \
  || echo "${default_remote}")
remote_branch=$( (git config "branch.${branch}.merge" \
  || echo "refs/heads/${branch}") | cut -d/ -f3-)

# push & save output
if [ -z "$*" ]; then
  # by default push to 'origin'
  # branch=$(git rev-parse --abbrev-ref HEAD) || exit "$?"
  # default_remote="origin"
  # remote=$(git config "branch.${branch}.remote" \
  #   || echo "${default_remote}")
  # remote_branch=$( (git config "branch.${branch}.merge" \
  #   || echo "refs/heads/${branch}") | cut -d/ -f3-)
  args="${remote} ${remote_branch}"
else
  args="$*"
fi
# echo "🚀 Pushing..."
# echo
push=$(git push --set-upstream "${args}" 2>&1)
exit_code="$?"

# preserve useful output returned by the remote server
# echo "${push}" | grep '^remote:'
# echo

if [ "${exit_code}" != 0 ]; then
  # push failed
  printf '%b\n' "${color_error}Ouch, push failed!${color_reset} ${push}"
  exit "${exit_code}"
elif echo "${push}" | grep "Everything up-to-date" >/dev/null; then
  # nothing to push
  echo "✌️ Git says everything is up-to-date!"
  exit 0
fi

# # parse relevant commit refs and let user know what we did
# # 1st-time push to new branch gets special treatment
# if echo "${push}" | grep "\[new branch\]" >/dev/null; then
#   parent=$(get_parent)
#   if [ -z "${parent}" ]; then
#     parent="main"
#   fi
#   refs="${parent}...${branch}"
#   echo "🚀  Pushed a new branch '${branch}' remotely"
# else
#   refs=$(echo "${push}" | awk '{ print $3}' | sed 's/\.\./\.\.\./')
#   echo "🚀  Pushed:"
#   echo "${push}"
# fi
# # parse output into a github compare url
# remote_url=$(git remote show "${remote}" -n | grep Push | awk '{ print $3 }')

exit 0
