#
# 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/
#
ARCH=arm64
BOOTSOURCE='https://github.com/rafaello7/u-boot-nanopi-m3'
BOOTBRANCH='branch:master'
BOOTDIR='u-boot-s5p6818'
BOOTPATCHDIR='legacy/u-boot-s5p6818'
BOOTSCRIPT='boot-s5p6818.cmd:boot.cmd'
BOOTENV_FILE='s5p6818.txt'
UBOOT_TARGET_MAP=";;boot.img bootemmc.img"
ATF_COMPILE="no"
case $BRANCH in
	legacy | current)
		KERNELSOURCE='https://github.com/armbian/linux'
		declare -g KERNEL_MAJOR_MINOR="4.14" # Major and minor versions of this kernel. See https://github.com/armbian/linux/blob/s5p6818/Makefile
		KERNELBRANCH='branch:s5p6818'
		;;
esac

CPUMIN="400000"
CPUMAX="1400000"
GOVERNOR=ondemand

write_uboot_platform() {
	if [[ "$2" != /dev/mmcblk0 ]]; then
		dd if=$1/boot.img of=$2 seek=1 status=noxfer > /dev/null 2>&1
	else
		dd if=$1/bootemmc.img of=$2 seek=1 status=noxfer > /dev/null 2>&1
	fi
}

uboot_custom_postprocess() {
	# 2GB differnt bl1 https://github.com/friendlyarm/linux-3.4.y/issues/3#issuecomment-387214487
	if [[ $BOARD == nanopct3plus ]]; then
		cp $SRC/packages/blobs/nanopi/2g-bl1-nanopi.bin boot.img
	else
		cp $SRC/packages/blobs/nanopi/1g-bl1-nanopi.bin boot.img
	fi
	i=0
	merge=""
	while [ $i -lt 512 ]; do
		val="00000000"
		[ $i -eq 68 ] && val="00060000"  # 0x44  load size
		[ $i -eq 72 ] && val="43bffe00"  # 0x48  load address
		[ $i -eq 76 ] && val="43c00000"  # 0x4c  launch address
		[ $i -eq 504 ] && val="68180300" # 0x1f8 version
		[ $i -eq 508 ] && val="4849534E" # 0x1fc "NSIH"
		# put in little endian
		vallo=${val#????}
		valhi=${val%????}
		merge=$merge"${vallo#??}${vallo%??}${valhi#??}${valhi%??}"
		i=$((i + 4))
	done
	echo $merge | xxd -r -p | dd of=boot.img seek=63 status=none
	cat u-boot.bin >> boot.img
	cp boot.img bootemmc.img
	printf "\2" | dd of=bootemmc.img bs=1 seek=80 conv=notrunc
}

family_tweaks() {
	:
}
