#!/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=
do_fetch=false

set_flags() {
	while [ $# -gt 0 ]; do
		case "$1" in
		-h | --help)
			echo "g-pull - pull changes from remote branch"
			echo " "
			echo "g-pull [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 "-f, --fetch                                                            fetch changes before pulling"
			exit 0
			;;
		-t=* | --target-branch=*)
			target_branch="${1#*=}"
			if [ -z "$target_branch" ]; then
				echo "${RED}Error: No target branch specified.$NC"
				exit 1
			fi
			;;
		-t | --target-branch)
			shift
			if [ $# -gt 0 ]; then
				target_branch="$1"
			else
				echo "${RED}Error: No target branch specified.$NC"
				exit 1
			fi
			;;
		-f | --fetch)
			do_fetch=true
			;;
		esac
		shift
	done
}

main() {
	set_flags "$@"
	validate_dependencies
	print_banner
	if [ -z "$target_branch" ]; then
		get_current_branch target_branch
	fi
	if [ "$do_fetch" = "true" ]; then
		print_message "${BLUE}Fetching changes...${NC}" 1
		fetch_changes "$target_branch"
		pull_changes "$target_branch" 2
		sync_submodules 3
		exit 0
	fi
	pull_changes "$target_branch" 1
	sync_submodules 2
}


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