#
# SPDX-License-Identifier: GPL-2.0
#
# Copyright (c) 2013-2023 Igor Pecovnik, igor@armbian.com
#
# This file is a part of the Armbian Build Framework
# https://github.com/armbian/build/
#
source "${BASH_SOURCE%/*}/include/meson64_common.inc"

# Fetch c2 blobs. Those are ancient, when first released by HK. Also used in meson-gxl.conf
function fetch_sources_tools__amlogic_odroidc2_blobs_fip() {
	fetch_from_repo "https://github.com/armbian/odroidc2-blobs" "odroidc2-blobs" "branch:master"
}

if [[ $BOARD == odroidc2 ]]; then
	UBOOT_TARGET_MAP=";;$SRC/cache/sources/odroidc2-blobs/bl1.bin.hardkernel u-boot.bin"
fi

uboot_custom_postprocess() {
	local fip_blobs_dir="$SRC/cache/sources/odroidc2-blobs/"

	if [[ $BOARD == odroidc2 ]]; then
		run_host_x86_binary_logged $fip_blobs_dir/fip_create --bl30 $fip_blobs_dir/gxb/bl30.bin \
			--bl301 $fip_blobs_dir/gxb/bl301.bin \
			--bl31 $fip_blobs_dir/gxb/bl31.bin \
			--bl33 u-boot.bin \
			fip.bin
		run_host_x86_binary_logged $fip_blobs_dir/fip_create --dump fip.bin
		run_host_command_logged cat $fip_blobs_dir/gxb/bl2.package fip.bin ">" boot_new.bin
		run_host_command_logged rm -fv u-boot.img
		run_host_x86_binary_logged $fip_blobs_dir/gxb/aml_encrypt_gxb --bootsig \
			--input boot_new.bin \
			--output u-boot.img
		run_host_command_logged rm -fv u-boot.bin
		run_host_command_logged dd if=u-boot.img of=u-boot.bin bs=512 skip=96 status=none
	fi

	if [[ $BOARD == nanopik2-s905 ]]; then
		run_host_command_logged mv -v u-boot.bin bl33.bin

		run_host_command_logged $fip_blobs_dir/blx_fix.sh $fip_blobs_dir/k2/bl30.bin \
			$fip_blobs_dir/k2/zero_tmp \
			$fip_blobs_dir/k2/bl30_zero.bin \
			$fip_blobs_dir/k2/bl301.bin \
			$fip_blobs_dir/k2/bl301_zero.bin \
			$fip_blobs_dir/k2/bl30_new.bin bl30

		run_host_x86_binary_logged $fip_blobs_dir/k2/fip_create --bl30 $fip_blobs_dir/k2/bl30_new.bin \
			--bl31 $fip_blobs_dir/k2/bl31.img \
			--bl33 bl33.bin \
			$fip_blobs_dir/k2/fip.bin

		run_host_x86_binary_logged $fip_blobs_dir/k2/fip_create --dump $fip_blobs_dir/k2/fip.bin

		run_host_command_logged python2 $fip_blobs_dir/acs_tool.pyc $fip_blobs_dir/k2/bl2.bin \
			$fip_blobs_dir/k2/bl2_acs.bin \
			$fip_blobs_dir/k2/acs.bin 0

		run_host_command_logged $fip_blobs_dir/blx_fix.sh $fip_blobs_dir/k2/bl2_acs.bin \
			$fip_blobs_dir/k2/zero_tmp \
			$fip_blobs_dir/k2/bl2_zero.bin \
			$fip_blobs_dir/k2/bl21.bin \
			$fip_blobs_dir/k2/bl21_zero.bin \
			$fip_blobs_dir/k2/bl2_new.bin bl2

		run_host_command_logged cat $fip_blobs_dir/k2/bl2_new.bin $fip_blobs_dir/k2/fip.bin ">" boot_new.bin

		run_host_x86_binary_logged $fip_blobs_dir/k2/aml_encrypt_gxb --bootsig \
			--input boot_new.bin \
			--output u-boot.bin

	fi
}

if [[ $BOARD == odroidc2 ]]; then

	write_uboot_platform() {
		dd if=$1/bl1.bin.hardkernel of=$2 bs=1 count=442 conv=fsync > /dev/null 2>&1
		dd if=$1/bl1.bin.hardkernel of=$2 bs=512 skip=1 seek=1 conv=fsync > /dev/null 2>&1
		dd if=$1/u-boot.bin of=$2 bs=512 seek=97 conv=fsync > /dev/null 2>&1
	}

fi
