#!/usr/bin/env bash

# Author: Santhosh Siva
# Date Created: 03-08-2025

# Description:
# A script to checkout branches, optionally stash changes, and manage git workflow efficiently.

# Resolve script directory (works with symlinks for npm global install)
SOURCE="${BASH_SOURCE[0]}"
while [ -L "$SOURCE" ]; do
  DIR="$(cd -P "$(dirname "$SOURCE")" && pwd)"
  SOURCE="$(readlink "$SOURCE")"
  [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE"
done
SCRIPT_DIR="$(cd -P "$(dirname "$SOURCE")" && pwd)"
source "$SCRIPT_DIR/utils"

target_branch=
should_force_push=false

set_flags() {
	while [ $# -gt 0 ]; do
		case "$1" in
		-h | --help)
			echo "g-push - push changes to remote branch"
			echo " "
			echo "g-push [options]"
			echo " "
			echo "options:"
			echo "-h, --help                                                             show brief help"
			echo "--target-branch BRANCH, --target-branch=BRANCH, -t=BRANCH, -t BRANCH   specify the target branch"
			echo "--stash-changes                                                        stash changes before proceeding"
			echo "--force                                                                force push changes to the target branch"
			exit 0
			;;
		-t=* | --target-branch=*)
			target_branch="${1#*=}"
			if [ -z "$target_branch" ]; then
				echo ""
				echo "${RED}Error: No target branch specified.$NC"
				exit 1
			fi
			;;
		-t | --target-branch)
			shift
			if [ $# -gt 0 ]; then
				target_branch="$1"
			else
				echo ""
				echo "${RED}Error: No target branch specified.$NC"
				exit 1
			fi
			;;
		-f | --force)
			should_force_push=true
			;;
		esac
		shift
	done
}

main() {
	set_flags "$@"
	validate_dependencies
	print_banner
	if [ -z "$target_branch" ]; then
		local current_branch
		get_current_branch current_branch
		push_changes "$current_branch" $should_force_push 1
		exit 0
	fi
	push_changes "$target_branch" $should_force_push 1
}


# Only run main if script is executed directly (not sourced)
if [ "${BASH_SOURCE[0]}" = "${0}" ]; then
	main "$@"
	exit 0
fi
