RED='\033[31m'
YELLOW='\033[33m'
GREEN='\033[32m'
BLUE='\033[34m'
NC='\033[0m'

SOURCE_ROOT=$(git rev-parse --show-toplevel)
DEFAULT_CONFIG=$(grep '^export KBUILD_DEFCONFIG=' $SOURCE_ROOT/Makefile | cut -d'=' -f2)
STABLE_MAJ_VER=$(grep VERSION $SOURCE_ROOT/Makefile | head -n1 | awk {'print $3'})
STABLE_MIN_VER=$(grep PATCHLEVEL $SOURCE_ROOT/Makefile | head -n1 | awk {'print $3'})
STABLE_BRANCH_ID=$(git log v${STABLE_MAJ_VER}.${STABLE_MIN_VER} --oneline -1 | awk -F' ' '{print $1}')
STABLE_BRANCH_FULLHASH=$(git rev-parse $STABLE_BRANCH_ID)
STABLE_BRANCH="6.12 6.6 6.1 5.15 5.10 5.4"
KYLIN_BRANCH="klas-v11-next klad-v11-next klinux-v11-next"

ARCH=$(uname -m)
Arch=$(echo $ARCH | sed -e s/i.86/x86/ -e s/x86_64/x86/ -e s/amd64/x86/ -e s/aarch64.*/arm64/ -e s/mips64el/mips/ -e s/loongarch64.*/loongarch/)

function gdct()
{
	GDC_TAG=$(git describe --contains $1 2>/dev/null | awk -F'~' '{print $1}' | awk -F'^' '{print $1}')
	echo $GDC_TAG
}

function better_gdct()
{
	TAGS=$(gdct $1)
	if [ -z $TAGS ]; then
		echo "> $(git describe --abbrev=0 $1)"
	else
		echo ">= $TAGS"
	fi
}

function branch2name()
{
	case "$1" in
		"klas-v11-next")
			printf "%-13s" "S11-SP0-DEVEL"
			;;
		"klad-v11-next")
			printf "%-13s" "D11-SP0-DEVEL"
			;;
		"klinux-v11-next")
			printf "%-13s" "V11-SP0-DEVEL"
			;;
	esac
}

function trim()
{
	local var="$*"
	var="$(echo -e "$var" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
	echo "$var"
}

# Logging functions
function log_info()
{
	[[ "$QUIET" != "1" ]] && echo -e "${GREEN}[INFO]${NC} $1" >&2
}

function log_warn()
{
	echo -e "${YELLOW}[WARN]${NC} $1" >&2
}

function log_error()
{
	echo -e "${RED}[ERROR]${NC} $1" >&2
}

function log_debug()
{
	[[ "$VERBOSE" == "1" ]] && echo -e "${BLUE}[DEBUG]${NC} $1" >&2
}

# Git utility functions
function check_git_is_installed()
{
	if ! command -v git &>/dev/null; then
		echo -e "${RED}Please install git first${NC}" >&2
		exit 1
	fi
}

function is_git_repository()
{
	if ! { [ -d .git ] || git rev-parse --git-dir >/dev/null 2>&1; }; then
		echo -e "${RED}This directory is not a git repository.${NC}" >&2
		exit 1
	fi
}

# Commit validation function
function validate_commit()
{
	local commit="$1"

	if [[ -z "$commit" ]]; then
		log_error "Commit ID cannot be empty"
		return 1
	fi

	# Check if commit exists and is valid
	if ! git rev-parse --verify "$commit" >/dev/null 2>&1; then
		log_error "Invalid commit ID: $commit"
		return 1
	fi
	return 0
}

