# U-Boot boot script for Raspberry Pi 3 with A/B boot
# This script will be converted to boot.scr by the post-image.sh script

echo "DEBUG: Starting boot process..."
echo "DEBUG: U-Boot version: ${ver}"
echo "DEBUG: Board: ${board_name}"

# Set load addresses
setenv kernel_addr_r 0x01000000
setenv fdt_addr_r 0x02000000
echo "DEBUG: Load addresses set - kernel: ${kernel_addr_r}, fdt: ${fdt_addr_r}"

# Print current environment variables
echo "DEBUG: Current boot variables:"
echo "DEBUG: active_part=${active_part}"
echo "DEBUG: active_root=${active_root}"
echo "DEBUG: bootcount=${bootcount}"
echo "DEBUG: bootlimit=${bootlimit}"

# Read and increment boot count
echo "DEBUG: Checking bootcount..."
if test ${bootcount} -lt ${bootlimit}; then
    echo "DEBUG: Incrementing bootcount from ${bootcount} to $((${bootcount} + 1))"
    setexpr bootcount ${bootcount} + 1
    echo "DEBUG: Saving environment..."
    saveenv
    echo "DEBUG: Environment saved"
fi

# If bootcount has reached bootlimit, switch to alternate boot
echo "DEBUG: Checking if bootcount >= bootlimit..."
if test ${bootcount} -ge ${bootlimit}; then
    echo "Boot failed too many times. Switching to alternate partition."
    echo "DEBUG: Running altbootcmd..."
    run altbootcmd
    echo "DEBUG: Resetting bootcount to 0"
    setenv bootcount 0
    echo "DEBUG: Saving environment..."
    saveenv
    echo "DEBUG: Environment saved"
fi

# List files in boot partition
echo "DEBUG: Listing files in boot partition:"
ls mmc 0:1

# Boot the system
echo "DEBUG: Preparing to boot from partition ${active_part}..."
echo "DEBUG: Will execute: bootcmd_${active_part}"
echo "DEBUG: bootcmd_${active_part}=${bootcmd_${active_part}}"
echo "DEBUG: Booting from partition ${active_part}..."
run bootcmd_${active_part}

# If we reach here, booting failed. Try alternate boot.
echo "DEBUG: Primary boot failed. Trying alternate partition..."
run altbootcmd