# $NetBSD: arm64.conf,v 1.15 2022/10/15 18:32:30 jmcneill Exp $
# ARM64 customization script used by mkimage
#
board=arm64
console=fb
resize=true
gpt=true
gpt_hybrid=true
gpt_create_flags="-p 16"
gpt_label_boot="EFI"
gpt_label_ffs="netbsd-root"

. ${DIR}/conf/evbarm.conf

kernel_GENERIC64="GENERIC64"

make_label() {
	make_label_evbarm
}

make_fstab() {
	make_fstab_evbarm
}

customize() {
	customize_evbarm
	cat >> "${mnt}/etc/rc.conf" << EOF
mdnsd=YES
devpubd=YES
wscons=\$(dev_exists wsdisplay0)
ec2_init=\$(is_cloud)
if checkyesno ec2_init ; then
	dhcpcd_flags="\$dhcpcd_flags -w"
else
	dhcpcd_flags="\$dhcpcd_flags -b"
fi
EOF
}

populate_common() {
	# Add EC2 init script
	cp ${DIR}/files/ec2_init ${mnt}/etc/rc.d/ec2_init
	echo "./etc/rc.d/ec2_init type=file uname=root gname=wheel mode=0555" \
	    >> "$tmp/selected_sets"

	# Rename kernel to netbsd.img
	mv "${mnt}/boot/netbsd-${kernel_GENERIC64}.img" "${mnt}/boot/netbsd.img"

	# Install EFI bootloader
	mkdir -p "${mnt}/boot/EFI/BOOT"
	cp "${release}/usr/mdec/bootaa64.efi" "${mnt}/boot/EFI/BOOT/bootaa64.efi"

	# Install kernel to root of the FFS partition
	${GZIP_CMD} -dc ${kernel}/netbsd-${kernel_GENERIC64}.gz > "${mnt}/netbsd"
	echo "./netbsd type=file uname=root gname=wheel mode=0755" \
	    >> "$tmp/selected_sets"
}


populate_rpi() {
	firmwaredir="${src}/external/broadcom/rpi-firmware/dist"
	firmwarefiles="LICENCE.broadcom bootcode.bin fixup4cd.dat fixup4.dat fixup_cd.dat fixup.dat start4cd.elf start4.elf start_cd.elf start.elf"

	cat > "${mnt}/boot/cmdline.txt" << EOF
root=NAME=${gpt_label_ffs} console=${console}
EOF

	cat > "${mnt}/boot/config.txt" << EOF
#
upstream_kernel=1
#
arm_64bit=1
os_prefix=dtb/broadcom/
cmdline=../../cmdline.txt
kernel=/netbsd.img
kernel_address=0x200000
enable_uart=1
force_turbo=0
EOF

	echo "${bar} installing firmware files ${bar}"
	(cd "${mnt}/boot" &&
		for f in ${firmwarefiles}; do
			echo " $f"
			cp "${firmwaredir}/${f}" .
		done
	)
}

populate() {
	echo "${bar} looking for kernel in ${kernel} ${bar}"
	kernels=""
	k="$kernel_GENERIC64"

	# .img kernel
	f="${kernel}/netbsd-${k}.img.gz"
	test -f "${f}" && kernels="${kernels} ${f}"

	# install files to /boot partition
	for k in ${kernels}; do
		tgt="$(basename ${k} | sed 's/\.gz$//')"
		echo "${bar} installing ${k} to /boot/${tgt} ${bar}"
		case "${k}" in
		*.gz)
			${GZIP_CMD} -dc "${k}" > "${mnt}/boot/${tgt}"
			;;
		*)
			cp "${k}" "${mnt}/boot/${tgt}"
			;;
		esac ||
			fail "Copy of ${k} to ${mnt}/boot/${tgt} failed"
	done

	# Board specific configuration
	populate_rpi

	# common configuration
	populate_common
}
