ARCH="arm64"

LINUXFAMILY="cix"
BOOTCONFIG="none"
ATF_COMPILE="no"
EXTERNAL_NEW="none"

SERIALCON="ttyAMA2"
KERNEL_COMPILER='aarch64-none-linux-gnu-'

case $BRANCH in

	current)
		if [[ $GITEE_SERVER == yes ]]; then
			KERNELSOURCE="https://gitee.com/orangepi-xunlong/orange-pi-6.1-cix.git"
		fi
		KERNELBRANCH='branch:orange-pi-6.1-cix'
		KERNELPATCHDIR='cix-current'
		LINUXCONFIG="linux-6.1-cix-p1-current"
		KERNEL_USE_GCC='> 12.0'
		ROOTFSCACHE_VERSION=12
	;;

	next)
		if [[ $GITEE_SERVER == yes ]]; then
			KERNELSOURCE="https://gitee.com/orangepi-xunlong/orange-pi-6.6-cix.git"
		fi
		KERNELBRANCH='branch:orange-pi-6.6-cix'
		KERNELPATCHDIR='cix-next'
		LINUXCONFIG="linux-6.6-cix-p1-next"
		KERNEL_USE_GCC='> 12.0'
		ROOTFSCACHE_VERSION=11
	;;
esac

family_tweaks_bsp() {
	:
}

function create_cix_deb() {
	local pkg_Name="$1"
	local PATH_CHANGELOGS=${EXTER}/cache/sources/component_cix-${BRANCH}/changelogs
	local PRIVATE_DEB_PACKAGES=("cix-dpu-ddk" "cix-npu-umd" "cix-isp-umd" "cix-gpu-umd" "cix-audio-dsp" "cix-hdcp2" "cix-noe-umd")
	local CIX_DEB_VERSION="0.01-1"

	display_alert "Building cix deb" "${pkg_Name}" "info"
	CHANGELOG="$PATH_CHANGELOGS/changelog.${pkg_Name}"
	if [[ ! -f "$CHANGELOG" ]]; then
		exit_with_error "changelog not found" "${CHANGELOG}"
	fi

	VERSION=$(grep -m 1 -oP '^\S+\s+\(\K[^)]+(?=\))' "$CHANGELOG")
	if [[ ! -n "$VERSION" ]]; then
		display_alert "get Version failed from: ${CHANGELOG}, will use default version" "1.0.0" "info"
		sleep 10
		VERSION="1.0.0"
	fi

	local pkg_Ver=$VERSION
	local pkg_private=false

	for str in "${PRIVATE_DEB_PACKAGES[@]}"; do
		if [[ "$str" == "$pkg_Name" ]]; then
			rm -rf ${PATH_OUT_DEB_PACKAGES}/$pkg_Name
			cp -r ${PATH_OUT_PRIVATE_DEB_PACKAGES}/${pkg_Name} ${PATH_OUT_DEB_PACKAGES}/$pkg_Name
			break
		fi
	done

	local build_deb_dir="${PATH_OUT_DEB_PACKAGES}/${pkg_Name}"

	case "$pkg_Name" in
	(*)
	CONTROL_CONTENT="Package: ${pkg_Name}
Version: ${pkg_Ver}
Architecture: arm64
Maintainer: Cix OS team
Depends: libc6 (>= 2.34)
Section: utils
Priority: optional
Description: $pkg_Name package"
	;;
	esac

	if [[ -e $build_deb_dir/usr/share/doc/$pkg_Name ]]; then
		if [[ -e $build_deb_dir/usr/share/doc/$pkg_Name/changelog.Debian.gz ]]; then
			rm -rf  $build_deb_dir/usr/share/doc/$pkg_Name/changelog.Debian.gz
		fi
	else
		mkdir -p $build_deb_dir/usr/share/doc/$pkg_Name
	fi

	cp $CHANGELOG $build_deb_dir/usr/share/doc/$pkg_Name/changelog.Debian
	gzip $build_deb_dir/usr/share/doc/$pkg_Name/changelog.Debian

	if [[ -e $PATH_OUT_PRIVATE_DEB_PACKAGES/copyright/$pkg_Name ]]; then
		mkdir -p $build_deb_dir/usr/share/doc/$pkg_Name
		cp $PATH_OUT_PRIVATE_DEB_PACKAGES/copyright/$pkg_Name/copyright $build_deb_dir/usr/share/doc/$pkg_Name
	fi

	if [[ -e "$build_deb_dir" ]]; then
		if [[ ! -e "$build_deb_dir/DEBIAN/control" ]]; then
			mkdir -p "$build_deb_dir/DEBIAN"
			echo "${CONTROL_CONTENT}" > "$build_deb_dir/DEBIAN/control"
		else
			sed -i "s/^Version: .*/Version: $pkg_Ver/" "$build_deb_dir/DEBIAN/control"
		fi

		chmod -R 755 "$build_deb_dir"
		chmod -R g-s "$build_deb_dir"
		rm -f ${PATH_OUT_DEB_PACKAGES}/${pkg_Name}_*.deb
		dpkg-deb -b --root-owner-group "$build_deb_dir" "${PATH_OUT_DEB_PACKAGES}/${pkg_Name}_${pkg_Ver}_arm64.deb" > /dev/null
		rm -rf ${PATH_OUT_DEB_PACKAGES}/${pkg_Name}
	else
		display_alert "deb path does not exist" "${build_deb_dir}" "info"
	fi
}

family_tweaks_kernel () {

	cix_open_src=${EXTER}/cache/sources/component_cix-${BRANCH}/cix_opensource
	PATH_OUT_PRIVATE_DEB_PACKAGES=${EXTER}/cache/sources/component_cix-${BRANCH}/cix_proprietary/cix_proprietary-debs
	PATH_OUT_DEB_PACKAGES=${DEB_STORAGE}/cix_debs-${BRANCH}

	export ARCH=arm64
	export KDIR=${SRC}/kernel/${KERNELBRANCH#branch:}
	export CROSS_COMPILE=${toolchain}/${KERNEL_COMPILER}

	[[ -d ${PATH_OUT_DEB_PACKAGES} ]] && rm -r ${PATH_OUT_DEB_PACKAGES}
	mkdir -p ${PATH_OUT_DEB_PACKAGES}

	cd ${cix_open_src}/vpu/vpu_driver/
	bash ./clean.sh > /dev/null
	scons $CTHREADS target=linux > /dev/null
	# build deb package
	pkg_Name="cix-vpu-driver"
	linux_version=$(strings ${SRC}/output/cix/Image | grep "Linux version" | cut -d' ' -f3 | head -1)
	build_deb_dir=${PATH_OUT_DEB_PACKAGES}/${pkg_Name}
	rm -rf ${build_deb_dir}
	install_dir=${build_deb_dir}/usr/share/cix/bin
	install_dir_kernel_modules=${build_deb_dir}/lib/modules/${linux_version}/extra
	install_dir_include=${build_deb_dir}/usr/share/cix/include
	install_dir_firmware="${build_deb_dir}/lib/firmware"
	mkdir -p ${install_dir}
	mkdir -p ${install_dir_kernel_modules}
	mkdir -p ${install_dir_include}
	mkdir -p ${install_dir_firmware}
	if [ -f bin/aarch64-none-linux-gnu/amvx.ko ]; then
		cp bin/aarch64-none-linux-gnu/amvx.ko ${install_dir_kernel_modules}
		cp include/aarch64-none-linux-gnu/mvx-v4l2-controls.h ${install_dir_include}
		if [[ -d "${PATH_OUT_PRIVATE_DEB_PACKAGES}/cix-vpu-umd/usr/lib/firmware" ]]; then
			cp -fp ${PATH_OUT_PRIVATE_DEB_PACKAGES}/cix-vpu-umd/usr/lib/firmware/* ${install_dir_firmware}/
		fi
		create_cix_deb "${pkg_Name}"
	else
		exit_with_error "vpu: amvx.ko module not exist"
	fi
	# finish build deb package
	cd - > /dev/null

	export COMPASS_DRV_BTENVAR_ARCH=${ARCH}
	export COMPASS_DRV_BTENVAR_KMD_DIR=driver
	export COMPASS_DRV_BTENVAR_KMD_VERSION=5.11.0
	export COMPASS_DRV_BTENVAR_KPATH=${KDIR}
	export BUILD_AIPU_VERSION_KMD=BUILD_ZHOUYI_V3
	export BUILD_TARGET_PLATFORM_KMD=BUILD_PLATFORM_SKY1
	export BUILD_NPU_DEVFREQ=y
	cd ${cix_open_src}/npu/npu_driver
	cp -f ${COMPASS_DRV_BTENVAR_KMD_DIR}/armchina-npu/include/armchina_aipu.h ${KDIR}/include/uapi/misc
	make $CTHREADS -C ${COMPASS_DRV_BTENVAR_KMD_DIR} ARCH=${COMPASS_DRV_BTENVAR_ARCH} CROSS_COMPILE=${CROSS_COMPILE} clean > /dev/null
	make $CTHREADS -C ${COMPASS_DRV_BTENVAR_KMD_DIR} ARCH=${COMPASS_DRV_BTENVAR_ARCH} CROSS_COMPILE=${CROSS_COMPILE} > /dev/null
	pkg_Name="cix-npu-driver"
	if [ -f ${COMPASS_DRV_BTENVAR_KMD_DIR}/aipu.ko ]; then
		# build deb package
		build_deb_dir=${PATH_OUT_DEB_PACKAGES}/${pkg_Name}
		rm -rf ${build_deb_dir}
		install_dir=${build_deb_dir}/lib/modules/${linux_version}/extra
		dkms_src_dir=${build_deb_dir}/usr/src
		mkdir -p ${install_dir}
		mkdir -p ${dkms_src_dir}
		cp ${COMPASS_DRV_BTENVAR_KMD_DIR}/aipu.ko ${install_dir}
		make $CTHREADS -C ${COMPASS_DRV_BTENVAR_KMD_DIR} ARCH=${COMPASS_DRV_BTENVAR_ARCH} CROSS_COMPILE=${CROSS_COMPILE} clean > /dev/null
		cp -r ${COMPASS_DRV_BTENVAR_KMD_DIR} ${dkms_src_dir}/aipu-${COMPASS_DRV_BTENVAR_KMD_VERSION}
		create_cix_deb "${pkg_Name}"
		rm -f $PATH_LINUX/include/uapi/misc/armchina_aipu.h
		# finish build deb package
	else
		exit_with_error "npu: aipu.ko module not exist"
	fi
	cd - > /dev/null

	export CONFIG_MALI_BASE_MODULES=y
	export CONFIG_MALI_MEMORY_GROUP_MANAGER=y
	export CONFIG_MALI_PROTECTED_MEMORY_ALLOCATOR=y
	export CONFIG_MALI_PLATFORM_NAME="sky1"
	export CONFIG_MALI_CSF_SUPPORT=y
	export CONFIG_MALI_CIX_POWER_MODEL=y
        cd ${cix_open_src}/gpu
	bash clean.sh > /dev/null
	gpu_driver_dir=${cix_open_src}/gpu/gpu_kernel/drivers
	if [[ "${DOCKER_MODE}" == "docker" ]]; then
		ARCH=arm64 make KCFLAGS="-D__ANDROID_COMMON_KERNEL__ -DUSING_DOCKER_MODE" $CTHREADS -C ${gpu_driver_dir}/base/arm/ > /dev/null
		ARCH=arm64 make KCFLAGS="-D__ANDROID_COMMON_KERNEL__ -DUSING_DOCKER_MODE" $CTHREADS -C ${gpu_driver_dir}/gpu/arm/ > /dev/null
	else
		ARCH=arm64 make $CTHREADS -C ${gpu_driver_dir}/base/arm/ > /dev/null
		ARCH=arm64 make $CTHREADS -C ${gpu_driver_dir}/gpu/arm/ > /dev/null
	fi
	# build deb package
	pkg_Name="cix-gpu-driver"
	build_deb_dir=${PATH_OUT_DEB_PACKAGES}/${pkg_Name}
	rm -rf ${build_deb_dir}
	install_dir=${build_deb_dir}/lib/modules/${linux_version}/extra
	mkdir -p ${install_dir}
	if [ -f ${gpu_driver_dir}/gpu/arm/midgard/mali_kbase.ko ]; then
		cp ${gpu_driver_dir}/base/arm/memory_group_manager/memory_group_manager.ko ${install_dir}
		cp ${gpu_driver_dir}/base/arm/protected_memory_allocator/protected_memory_allocator.ko ${install_dir}
		cp ${gpu_driver_dir}/gpu/arm/midgard/mali_kbase.ko ${install_dir}
		create_cix_deb "${pkg_Name}"
	else
		exit_with_error "gpu: amxv.ko module not exist"
	fi
	# finish build deb package
	cd - > /dev/null

	local DRV_DIR=${cix_open_src}/isp/isp_driver
	MODULE=armcb_isp_v4l2
	cd "${DRV_DIR}"
	make ARCH=${ARCH} CROSS_COMPILE=${CROSS_COMPILE} $CTHREADS PATH_ROOT=${KDIR} clean > /dev/null
	make ARCH=${ARCH} CROSS_COMPILE=${CROSS_COMPILE} $CTHREADS PATH_ROOT=${KDIR} build > /dev/null
	if [ -f ${DRV_DIR}/${MODULE}.ko ]; then
		# build deb package
		pkg_Name="cix-isp-driver-v4l2"
		build_deb_dir=${PATH_OUT_DEB_PACKAGES}/${pkg_Name}
		rm -rf ${build_deb_dir}
		install_dir=${build_deb_dir}/lib/modules/${linux_version}/extra
		mkdir -p ${install_dir}
		cp ${DRV_DIR}/${MODULE}.ko ${install_dir}
		create_cix_deb "${pkg_Name}"
	else
		exit_with_error "${MODULE}.ko module not exist"
	fi
	cd - > /dev/null

	rm ${SRC}/output/debs/linux-dtb* > /dev/null 2>&1
	rm ${SRC}/output/debs/linux-libc-dev* > /dev/null 2>&1
}

install_cix_debs() {

	[[ $BUILD_DESKTOP != yes ]] && return
	[[ ${RELEASE} == noble ]] && return

	display_alert "Installing" "Cix debs" "info"

	local POOL_PATH=${EXTER}/cache/sources/component_cix-${BRANCH}/cix_proprietary/cix_proprietary-debs
	local DEB_PATH=${SDCARD}/root/debs

	mkdir -p ${DEB_PATH}
	if [[ $BRANCH == current ]]; then
		cp -fp $POOL_PATH/pool/main/*/*/*.deb ${DEB_PATH}/
		cp -fp $POOL_PATH/pool/main/*/*.deb   ${DEB_PATH}/
	fi
	cp ${EXTER}/cache/sources/component_cix-${BRANCH}/debs/*.deb ${DEB_PATH}/

	chroot $SDCARD /bin/bash -e -c "apt-get -y --allow-downgrades install /root/debs/*.deb"
	run_on_sdcard "systemctl mask swap.target"
	run_on_sdcard "systemctl enable cix_resume.service"
	run_on_sdcard "systemctl enable cix_resume_prepare.service"
	rm ${DEB_PATH} -rf

	run_on_sdcard "EBIAN_FRONTEND=noninteractive apt-get -yqq install pulseaudio"
	run_on_sdcard "EBIAN_FRONTEND=noninteractive apt-get -yqq remove wireplumber"
	run_on_sdcard "EBIAN_FRONTEND=noninteractive apt-get -yqq remove pipewire-pulse"
	dpkg_install_deb_chroot "${EXTER}/cache/sources/component_cix-${BRANCH}/debs_manual/gnome-core_arm64.deb"

	rm $SDCARD/root/*.deb >/dev/null 2>&1
}

family_tweaks() {

	#install_cix_debs
	install_balenaEtcher
	#install_wiringop

	if [[ -L "${SDCARD}/usr/lib/policykit-1/polkit-agent-helper-1" ]]; then
		chmod 5755 ${SDCARD}/usr/lib/policykit-1/polkit-agent-helper-1
	fi

	cp ${DEB_STORAGE}/cix_debs-${BRANCH} ${SDCARD}/root/ -rf
	run_on_sdcard "apt-get -y --allow-downgrades install /root/cix_debs-${BRANCH}/*.deb"

	linux_version=$(strings ${SRC}/output/cix/Image | grep "Linux version" | cut -d' ' -f3 | head -1)

	run_on_sdcard "depmod -a $linux_version/"
	rm -rf ${SDCARD}/root/cix_debs-${BRANCH}
	rm -rf ${SDCARD}/usr/local/test.mp4

	touch ${SDCARD}/root/.Xauthority

	mv ${SDCARD}/usr/share/cix/bin/spidev_test ${SDCARD}/usr/bin/ >/dev/null 2>&1
	rm ${SDCARD}/usr/share/cix/bin/isp_app >/dev/null 2>&1

	sed -i 's/^ENABLED=true$/ENABLED=false/' ${SDCARD}/etc/default/orangepi-zram-config

	run_on_sdcard "systemctl --no-reload enable getty@tty1.service >/dev/null 2>&1"
	if [[ ${RELEASE} == bookworm ]]; then
		run_on_sdcard "systemctl mask ssh.socket" >/dev/null 2>&1
	fi

	rsync -a --chown=root:root "${EXTER}"/packages/bsp/overlays_cix/* ${SDCARD}/
	if [[ $BRANCH == next ]]; then
		rsync -a --chown=root:root "${EXTER}"/packages/bsp/overlays_cix_next/* ${SDCARD}/
	fi
	run_on_sdcard "systemctl --no-reload enable isp-daemon.service >/dev/null 2>&1"

	rm $SDCARD/root/*.deb >/dev/null 2>&1
}

install_balenaEtcher(){

	if [[ $BUILD_DESKTOP == yes && $install_balena_etcher == yes ]]; then

		[[ ${RELEASE} == noble ]] && return

		balena_etcher_deb=balena-etcher-electron_1.7.9+5945ab1f_arm64.deb
		balena_etcher_url="https://github.com/Itai-Nelken/BalenaEtcher-arm/releases/download/v1.7.9/${balena_etcher_deb}"
		balena_etcher=${EXTER}/cache/debs/arm64/${balena_etcher_deb}

		if [[ ! -f ${balena_etcher} ]]; then
			wget -P ${EXTER}/cache/debs/arm64 ${balena_etcher_url}
		fi

		install_deb_chroot ${balena_etcher}
		rm $SDCARD/root/*.deb >/dev/null 2>&1
	fi
}
