#!/bin/bash

warning() {
	read -p $'Is there an SD card with the default image currently flashed and connected? [Y\n] ' option

	while [ "$option" != "Y" ] && [ "$option" != "y" ] && [ "$option" != "N" ] && [ "$option" != "n" ] && [ "$option" != "" ]
	do
		read -p "Please input y or n. [Y/n] " option
	done

	if [ "$option" == "N" ] || [ "$option" == "n" ]
	then
		exit 1
	fi
}

install_toolchain() {
	wget https://developer.arm.com/-/media/Files/downloads/gnu/12.3.rel1/binrel/arm-gnu-toolchain-12.3.rel1-x86_64-aarch64-none-linux-gnu.tar.xz
	tar -xvf arm-gnu-toolchain-12.3.rel1-x86_64-aarch64-none-linux-gnu.tar.xz
	export ARCH=arm64
	export CROSS_COMPILE=$PWD/arm-gnu-toolchain-12.3.rel1-x86_64-aarch64-none-linux-gnu/bin/aarch64-none-linux-gnu-
}

clone_repos() {
	git clone -b ti-linux-6.1.y https://git.ti.com/git/ti-linux-kernel/ti-linux-kernel.git
	git clone -b ti-am65-cpsw-nuss_6.1_6.6 https://gitlab.com/npitre/ethercat.git
}

patch_kernel() {
	cd ti-linux-kernel
	git am 0001-am65-cpsw-switchdev.c-export-switchdev-functions.patch
	git am 0002-ti_am65_cpsw_nuss-.config-add-am65_cpsw_nuss-module-.patch
	git am 0003-soc-ti-k3-ringacc-Add-check-for-DMA-descriptor.patch
	cd ../
}

build_kernel_without_driver() {
	cd ti-linux-kernel
	make defconfig ti_arm65_prune.config ti_am65_cpsw_nuss_remove.config
	make -j`nproc` Image modules
	sudo cp arch/arm64/boot/Image /media/`whoami`/root/boot/
	make INSTALL_MOD_PATH=/media/`whoami`/root/ modules_install
	cd ../
}

build_ethercat() {
	cd ethercat
	./bootstrap
	./configure \
		--sysconfdir=/opt/etherlab --prefix=/opt/etherlab --with-linux-dir=$PWD/../ti-linux-kernel \
		--with-module-dir=/etherlab --enable-generic=no --enable-8139too=no --enable-eoe=no \
		--host=aarch64-none-linux-gnu --target=aarch64-none-linux-gnu \
		--enable-am65cpsw=yes --with-am65cpsw-kernel=6.1
	make -j`nproc`
	make -j`nproc` modules
	sudo chown -R `whoami` /media/`whoami`/root/
	make DESTDIR=/media/`whoami`/root/ install
	make INSTALL_MOD_PATH=/media/`whoami`/root/ modules_install
	cd ../
}

build_kernel_with_module() {
	cd ti-linux-kernel
	make defconfig ti_arm64_prune.config ti_am65_cpsw_nuss_module.config
	make -j`nproc` Image modules
	sudo cp arch/arm64/boot/Image /media/`whoami`/root/boot/
	sudo make INSTALL_MOD_PATH=/media/`whoami`/root/ modules_install
	cd ../
}

copy_setup_script() {
	cp setup_target.sh /media/`whoami`/root/home/root/
}

warning
install_toolchain
clone_repos
patch_kernel
build_kernel_without_driver
build_ethercat
build_kernel_with_module
copy_setup_script