#
# SPDX-License-Identifier: GPL-2.0
# Copyright (c) 2023 Ricardo Pardini <ricardo@pardini.net>
# This file is a part of the Armbian Build Framework https://github.com/armbian/build/
#

declare -g LINUXFAMILY="meson-s4t7"
declare -g ARCH="arm64"
declare -g ATF_COMPILE="no"

declare -g BLUETOOTH_HCIATTACH_PARAMS="-s 115200 /dev/ttyS1 bcm43xx 2000000" # For the bluetooth-hciattach extension
enable_extension "bluetooth-hciattach"                                       # Enable the bluetooth-hciattach extension

# Determine kernel
case $BRANCH in

	legacy)
		declare -g KERNEL_MAJOR_MINOR="5.15"                           # Major and minor versions of this kernel. For mainline caching.
		declare -g KERNELSOURCE="${GITHUB_SOURCE}/khadas/linux.git" # Khadas kernel
		declare -g KERNELBRANCH="branch:khadas-vims-5.15.y"            # Branch or tag to build from. It should match MAJOR_MINOR
		declare -g KERNELPATCHDIR="archive/meson-s4t7-5.15"
		declare -g COMMON_DRIVERS_SOURCE="${GITHUB_SOURCE}/khadas/common_drivers"
		declare -g EXTRAWIFI=no
		;;

esac

# Lets build uboot from source
BOOTSOURCE="${GITHUB_SOURCE}/khadas/u-boot.git"
BOOTBRANCH="tag:khadas-vims-u-boot-2019.01-v1.6.4-release"
BOOTPATCHDIR="u-boot-meson-s4t7"
BOOTENV_FILE='meson.txt'
BOOTSCRIPT="boot-meson-s4t7.cmd:boot.cmd"
FORCE_BOOTSCRIPT_UPDATE="yes"
FORCE_UBOOT_UPDATE="yes"
UBOOT_TARGET_MAP=";;fip/_tmp/u-boot.bin.sd.bin.signed:u-boot.bin.sd.bin.signed"

## funny enough, the uboot+fip blobs go in the same spot as normal meson64...
function write_uboot_platform() {
	dd if="$1/u-boot.bin.sd.bin.signed" of="$2" conv=fsync,notrunc bs=442 count=1       #> /dev/null 2>&1
	dd if="$1/u-boot.bin.sd.bin.signed" of="$2" conv=fsync,notrunc bs=512 skip=1 seek=1 #> /dev/null 2>&1
}

# We'll need xxd to build the fip blobs
function add_host_dependencies__khadas_fips_needs_xxd() {
	display_alert "Adding xxd to host dependencies" "for khadas bootloader compile" "debug"
	declare -g EXTRA_BUILD_DEPS="${EXTRA_BUILD_DEPS} xxd"
}

function fetch_sources_tools__meson_s4t7_download_uboot_toolchain() {
	display_alert "$BOARD" "preparing linaro toolchain for bootloader fip" "info"

	if [[ "${HOSTARCH}" != "amd64" ]]; then
		exit_with_error "vim1s/vim4 uboot requires amd64 system to build"
	fi

	declare tversion="7.3.1-2018.05"
	declare tbasedir="${SRC}/cache/toolchain"
	declare tdir="${tbasedir}/gcc-linaro-${tversion}-x86_64_aarch64-elf"
	declare tfile="gcc-linaro-${tversion}-x86_64_aarch64-elf.tar.xz"
	declare turl="https://dl.armbian.com/_toolchain/${tfile}"

	if [[ ! -d "${tdir}" ]]; then
		run_host_command_logged wget --progress=dot:giga -O "${tbasedir}/${tfile}" "${turl}"
		run_host_command_logged tar -C "${tbasedir}" -xf "${tbasedir}/${tfile}"
		run_host_command_logged rm -fv "${tbasedir}/${tfile}"
	fi

	# Symlinks are not enough: riscv-none-embed-ld: cannot find -lgcc, So we need to add the toolchain to the PATH
	export PATH="${tdir}/bin:${PATH}"

	display_alert "$BOARD" "preparing riscv toolchain for bootloader fip" "info"

	declare tos="x64"
	[[ "${HOSTARCH}" == "arm64" ]] && tos="arm64"
	[[ "${HOSTARCH}" == "armhf" ]] && tos="arm"
	declare tversion="8.3.0-1.2"
	declare tbasedir="${SRC}/cache/toolchain"
	declare tdir="${tbasedir}/xpack-riscv-none-embed-gcc-${tversion}"
	declare tfile="xpack-riscv-none-embed-gcc-${tversion}-linux-${tos}.tar.gz"
	declare turl="https://dl.armbian.com/_toolchain/${tfile}"

	mkdir -p "${tbasedir}"

	if [[ ! -d "${tdir}" ]]; then
		run_host_command_logged wget --progress=dot:giga -O "${tbasedir}/${tfile}" "${turl}"
		run_host_command_logged tar -C "${tbasedir}" -xzf "${tbasedir}/${tfile}"
		run_host_command_logged rm -fv "${tbasedir}/${tfile}"
	fi

	# Symlinks are not enough: riscv-none-embed-ld: cannot find -lgcc, So we need to add the toolchain to the PATH
	declare -g -r PRE_TOOLCHAIN_PATH="${PATH}"
	export PATH="${tdir}/bin:${PATH}"
}

# Invoke fip build script after the u-boot target
function build_custom_uboot__meson_s4t7_build_custom_uboot() {
	: "${KHADAS_BOARD_ID:?KHADAS_BOARD_ID not set}"
	display_alert "$BOARD" "building fip" "info"

	patch_uboot_target

	if [[ $CREATE_PATCHES == yes ]]; then
		return 0
	fi

	export CROSS_COMPILE="aarch64-elf-"
	rm -rf "${PWD}"/fip/_tmp
	run_host_command_logged bash fip/mk_script.sh "${KHADAS_BOARD_ID}" "${PWD}"
	loop_over_uboot_targets_and_do deploy_built_uboot_bins_for_one_target_to_packaging_area
	declare -g EXTENSION_BUILT_UBOOT=yes
}

function armbian_kernel_config__add_khadas_common_drivers() {
	if [[ ! -f .config ]]; then
		display_alert "$BOARD" "Fetching khadas common drivers git info" "info"

		common_drivers_cache_ttl_seconds=3600
		declare -A GIT_INFO_COMMON_DRIVERS=([GIT_SOURCE]="${COMMON_DRIVERS_SOURCE}" [GIT_REF]="${KERNELBRANCH}")

		if [[ "${KERNEL_GIT_CACHE_TTL}" != "" ]]; then
			common_drivers_cache_ttl_seconds="${KERNEL_GIT_CACHE_TTL}"
		fi

		memoize_cache_ttl=$common_drivers_cache_ttl_seconds run_memoized GIT_INFO_COMMON_DRIVERS "git2info" memoized_git_ref_to_info

		# Hack to ensure that we will recreate kernel if common_drivers source changes
		kernel_config_modifying_hashes+=( "khadas_common_drivers=${GIT_INFO_COMMON_DRIVERS[SHA1]}" )
	fi
}

function kernel_copy_extra_sources__khadas_common_drivers() {
	display_alert "$BOARD" "Copying khadas common drivers" "info"

	common_drivers_git_bare_tree="${SRC}/cache/git-bare/khadas_common_drivers"
	declare common_drivers_git_bare_tree_done_marker="${common_drivers_git_bare_tree}/.git/armbian-bare-tree-done"

	if [[ ! -d "${common_drivers_git_bare_tree}" || ! -f "${common_drivers_git_bare_tree_done_marker}" ]]; then
		if [[ -d "${common_drivers_git_bare_tree}" ]]; then
			rm -rf "${common_drivers_git_bare_tree}"
		fi

		run_host_command_logged git clone  --tags --no-checkout \
			"${COMMON_DRIVERS_SOURCE}" "${common_drivers_git_bare_tree}"

		touch "${common_drivers_git_bare_tree_done_marker}"
	fi

	git_ensure_safe_directory "${common_drivers_git_bare_tree}"

	GIT_FIXED_WORKDIR="${LINUXSOURCEDIR}/common_drivers" \
		GIT_BARE_REPO_FOR_WORKTREE="${common_drivers_git_bare_tree}" \
		GIT_BARE_REPO_INITIAL_BRANCH="${KERNELBRANCH#*:}" \
		fetch_from_repo "${COMMON_DRIVERS_SOURCE}" "common_drivers:${KERNEL_MAJOR_MINOR}" "${KERNELBRANCH}" "yes"
}

function pre_package_kernel_headers__copy_common_drivers_header_include_mk_file() {
	display_alert "Copy common_drivers/header_include.mk file in kernel headers"
	declare makefile_destination="${headers_target_dir}"/common_drivers
	run_host_command_logged mkdir -p ${makefile_destination}
	run_host_command_logged cp ${kernel_work_dir}/common_drivers/header_include.mk ${makefile_destination}/
	run_host_command_logged cp -r ${kernel_work_dir}/common_drivers/include ${makefile_destination}/
}

function pre_package_kernel_image__copy_meson_s4t7_overlays() {
	display_alert "Copy meson s4t7 overlays"
	declare dtbo_destination="${tmp_kernel_install_dirs[INSTALL_DTBS_PATH]}"/amlogic

	# the directory structure is changed between 5.4 and 5.15 kernel
	# Lets make it consistent
	run_host_command_logged mkdir -p ${dtbo_destination}
	run_host_command_logged mv "${tmp_kernel_install_dirs[INSTALL_DTBS_PATH]}"/*.dtb ${dtbo_destination}/

	run_host_command_logged cp -r ${SRC}/patch/kernel/${KERNELPATCHDIR}/overlay ${dtbo_destination}/

	display_alert "Enable Device Tree Overlays"
	run_host_command_logged ln -sf amlogic/overlay "${tmp_kernel_install_dirs[INSTALL_DTBS_PATH]}"/overlay
}

function post_family_tweaks_bsp__disable_uinitrd_generation() {
	if [[ -f "${destination}"/etc/initramfs/post-update.d/99-uboot ]]; then
		run_host_command_logged rm "${destination}"/etc/initramfs/post-update.d/99-uboot
	fi
}

function image_specific_armbian_env_ready__enable_earlycon() {
    display_alert "Enabling earlycon"
    run_host_command_logged echo "earlycon=on" >>${SDCARD}/boot/armbianEnv.txt
}

function post_family_tweaks_bsp__add_fan_service() {
	if [[ ${BRANCH} = "legacy" ]]; then
		run_host_command_logged cp -R "${SRC}"/packages/bsp/meson-s4t7/common/* "${destination}"/
		run_host_command_logged cp -R "${SRC}"/packages/bsp/meson-s4t7/${BOARD}/* "${destination}"/
	fi
}

function meson_s4t7_board_side_bsp_cli_postrm() { # not run here
	if [[ remove == "$1" ]] || [[ abort-install == "$1" ]]; then
		cp /usr/share/initramfs-tools/modules /etc/initramfs-tools/modules
	fi
}

function post_family_tweaks_bsp__add_postrm_hook() {
	display_alert "$BOARD" "Adding postrm hook to restore /etc/initramfs-tools/modules file" "info"
	postrm_functions+=(meson_s4t7_board_side_bsp_cli_postrm)
}
