#!/usr/bin/env bash

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

# Description:
# A script to quickly reset your working directory to the latest changes from the remote branch.
# In case you ran this command by mistake, you can use the `git stash apply` command to restore your changes.

# 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"

set_flags() {
	while [ $# -gt 0 ]; do
		case "$1" in
		-h | --help)
			echo "g-rto - reset to remote branch"
			echo " "
			echo "g-rto [options]"
			echo " "
			echo "options:"
			echo "-h, --help          show brief help"
			exit 0
			;;
		*)
			echo ""
			echo "${RED}Unknown option:${NC} $1"
			exit 1
			;;
		esac
		shift
	done
}

main() {
	set_flags "$@"
	validate_dependencies git figlet lolcat
	print_banner
	get_current_branch target_branch
	stash_changes true 1
	print_message ""

	print_message "${BLUE}Fetching changes from remote/${target_branch}...${NC}" 2
	fetch_changes "$target_branch"
	print_message ""

	reset_to_target_branch "$target_branch" 3
	pull_changes "$target_branch" 4
	sync_submodules 5
}


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