#!/bin/bash

gitCheckGitDetails()
{
	# Source all config files to get current values
	sourceScanFiles "libreportal_configs"
	
	CFG_GIT_USER="${CFG_GIT_USER:-changeme}"
	if [[ -z "$CFG_GIT_USER" ]] || [[ "$CFG_GIT_USER" == "changeme" ]]; then
		echo ""
		echo "Git Authentication Method:"
		echo "1) Login required (username + token)"
		echo "2) Authenticationless (public repos / SSH keys)"
		echo ""
		while true; do
			read -p "Choose option [1-2]: " git_auth_choice
			case "$git_auth_choice" in
				1)
					while true; do
						echo "Enter Git username:"
						read -r NEW_GIT_USER
						if [[ -n "$NEW_GIT_USER" ]]; then
							updateConfigOption "CFG_GIT_USER" "$NEW_GIT_USER"
							echo "Updating Git Username"
							break
						else
							echo "Username cannot be empty for login authentication."
						fi
					done
					break
					;;
				2)
					updateConfigOption "CFG_GIT_USER" "empty"
					updateConfigOption "CFG_GIT_KEY" "empty"
					echo "Using authenticationless Git access."
					break
					;;
				*)
					echo "Invalid option. Choose 1 or 2."
					;;
			esac
		done
	fi

	# Only ask for token if user is not empty and token is missing
	if [[ "$CFG_GIT_USER" != "empty" && "$CFG_GIT_USER" != "" ]]; then
		CFG_GIT_KEY="${CFG_GIT_KEY:-changeme}"
		if [[ -z "$CFG_GIT_KEY" ]] || [[ "$CFG_GIT_KEY" == "changeme" ]]; then
			while true; do
				echo "Please enter your Git access token:"
				read -rs NEW_GIT_KEY
				if [[ -n "$NEW_GIT_KEY" ]]; then
					updateConfigOption "CFG_GIT_KEY" "$NEW_GIT_KEY"
					echo "Updating Git Token"
					break
				else
					echo "Git token cannot be empty for login authentication."
				fi
			done
		fi
	fi

	CFG_GIT_URL="${CFG_GIT_URL:-changeme}"
	if [[ -z "$CFG_GIT_URL" ]] || [[ "$CFG_GIT_URL" == "changeme" ]]; then
		while true; do
			echo "Please enter your Git repository URL:"
			read -r NEW_GIT_URL
			if [[ -n "$NEW_GIT_URL" ]]; then
				# Validate and fix Git URL
				NEW_GIT_URL=$(validateAndFixGitUrl "$NEW_GIT_URL")
				updateConfigOption "CFG_GIT_URL" "$NEW_GIT_URL"
				echo "Updating Git URL"
				break
			else
				echo "Git URL cannot be empty"
			fi
		done
	fi
	
	# Reload updated config
	sourceScanFiles "libreportal_configs"
}