# Library of functions that reproduce hashing behavior in internal/rukpak/convert/registryv1.go:generate_name()
# This is used to generate unique names for the ClusterRoles generated by O-C during bundle installation

base36encode() {
    if [[ -z "$1" || ! "$1" =~ ^[0-9a-fA-F]+$ ]]; then
        echo "Invalid input. Please provide a hexadecimal number."
        return 1
    fi

    # Convert hexadecimal to decimal
    local bigint
    bigint=$(echo "ibase=16; $1" | bc)

    # Convert decimal to base 36
    local base36=""
    while [ "$(echo "$bigint > 0" | bc)" -eq 1 ]; do
        remainder=$(echo "$bigint % 36" | bc)
        bigint=$(echo "$bigint / 36" | bc)

        if [ "$remainder" -lt 10 ]; then
            base36="${remainder}${base36}"
        else
            # Convert remainder (10-35) to corresponding ASCII letter ('a'-'z')
            val=$((remainder + 87))
            char=$(echo "$val" | awk '{printf "%c", $1}')
            base36="${char}${base36}"
        fi
    done
    echo "$base36"
}

deep_hash_object() {
    local obj="$1"

    # Compute SHA-224 hash and convert to uppercase for consistency
    local hash_hex
    hash_hex=$(echo "$obj" | sha224sum | awk '{print toupper($1)}')

    # Encode the hash to base36
    local base36_hash
    base36_hash=$(base36encode "${hash_hex}")
    echo "${base36_hash}"
}

# Function to generate a name based on the base string and hashed object
generate_name() {
    local base="$1"
    local obj="$2"
    local max_name_length=63  # Define the maximum name length (similar to DNS limits)

    # Generate a hash from the object using deep_hash_object function
    local hash_str
    hash_str=$(deep_hash_object "$obj")

    # Check if the combined length exceeds the maximum length
    if [ $((${#base} + ${#hash_str})) -gt $max_name_length ]; then
        # Truncate the base string
        base="${base:0:$((max_name_length - ${#hash_str} - 1))}"
    fi

    # Return the concatenated string
    echo "${base}-${hash_str}"
}