#!/bin/sh

set -e

FWUP_CONFIG=$NERVES_DEFCONFIG_DIR/fwup.conf
IMAGES_DIR=$BINARIES_DIR

# For Amlogic A311D, we need to build the FIP (Firmware Image Package)
# that contains U-Boot + BL2 + BL30 + BL31 + DDR firmware
AMLOGIC_DIR=${BINARIES_DIR}/amlogic-boot-fip
FIP_DIR=${BINARIES_DIR}/fip

if [ -f "$IMAGES_DIR/u-boot.bin" ] && [ -d "$AMLOGIC_DIR" ]; then
    echo "Building Amlogic FIP for SD card boot..."
    mkdir -p "${FIP_DIR}"

    # Run the FIP build script
    (cd "${AMLOGIC_DIR}" && \
        ./build-fip.sh khadas-vim3 \
        "${BINARIES_DIR}"/u-boot.bin \
        "${FIP_DIR}")

    if [ -f "${FIP_DIR}/u-boot.bin.sd.bin" ]; then
        echo "Successfully created u-boot.bin.sd.bin for SD card boot"

        # Extract bootstrap from mainline U-Boot FIP build
        echo "Extracting SD card bootstrap from mainline U-Boot FIP..."
        dd if="${FIP_DIR}/u-boot.bin.sd.bin" of="$IMAGES_DIR/u-boot-bootstrap.bin" \
            bs=1 count=440 status=none
        BOOTSTRAP_HEX=$(xxd -p -c 440 "$IMAGES_DIR/u-boot-bootstrap.bin" | tr -d '\n')
        echo "Using mainline U-Boot 2025.10 bootstrap"

        # Inject bootstrap code into fwup.conf
        # Modify source fwup.conf in place - it will be copied to images by common post-createfs.sh
        sed -i "s/bootstrap-code = \"[^\"]*\"/bootstrap-code = \"$BOOTSTRAP_HEX\"/" "$FWUP_CONFIG"
        echo "Injected bootstrap code into fwup.conf"

        # Create skip512 version (skip first 512 bytes for sector 1 onwards)
        dd if="${FIP_DIR}/u-boot.bin.sd.bin" of="$IMAGES_DIR/u-boot-skip512.bin" \
            bs=512 skip=1 status=none
        echo "Created u-boot-skip512.bin for writing to sector 1 onwards"

        # Copy the SD card binary to images
        cp "${FIP_DIR}/u-boot.bin.sd.bin" "$IMAGES_DIR/"
        echo "Copied u-boot.bin.sd.bin to images directory"
    else
        echo "ERROR: Failed to build u-boot.bin.sd.bin"
        exit 1
    fi
else
    echo "WARNING: Either u-boot.bin or amlogic-boot-fip directory not found"
    echo "  u-boot.bin exists: $([ -f "$IMAGES_DIR/u-boot.bin" ] && echo "yes" || echo "no")"
    echo "  amlogic-boot-fip exists: $([ -d "$AMLOGIC_DIR" ] && echo "yes" || echo "no")"
fi

# Create boot.scr from boot.cmd
BOOT_CMD="${NERVES_DEFCONFIG_DIR}/uboot/boot.cmd"
MKIMAGE="${HOST_DIR}/bin/mkimage"

if [ -f "$BOOT_CMD" ]; then
    if [ -x "$MKIMAGE" ]; then
        echo "Creating boot.scr from boot.cmd..."
        "$MKIMAGE" -C none -A arm64 -T script -d "$BOOT_CMD" "$IMAGES_DIR/boot.scr"
        echo "Successfully created boot.scr"
    else
        echo "WARNING: mkimage not found at $MKIMAGE, creating empty boot.scr"
        # Create an empty boot.scr as placeholder
        touch "$IMAGES_DIR/boot.scr"
    fi
else
    echo "WARNING: boot.cmd not found at $BOOT_CMD"
fi

# Run the common post-image processing for nerves
$BR2_EXTERNAL_NERVES_PATH/board/nerves-common/post-createfs.sh $TARGET_DIR $FWUP_CONFIG
