#!/bin/bash

#script that prepares the L4T folder for Jetpack 7.1

SOURCES=$1

if [[ "$SOURCES" == "-h" ]]; then
	echo "This script creates the Linux_for_Tegra folder for Jetpack 7.2 to flash the Nvidia T5000 + Auvidea carrier X242"
	echo "syntax: prepare_JP7_2_L4T_folder.sh [-s]"
	echo "[-s] = if this parameter is given the sources will also be downloaded"
	echo "[-h] = display this message"
else 
	echo "Download Nvidia sources"
	[ -f ./Jetson_Linux_R39.2.0_aarch64.tbz2 ] || wget https://developer.nvidia.com/downloads/embedded/L4T/r39_Release_v2.0/release/Jetson_Linux_R39.2.0_aarch64.tbz2
	
	[ -f ./Tegra_Linux_Sample-Root-Filesystem_R39.2.0_aarch64.tbz2 ] || wget https://developer.nvidia.com/downloads/embedded/L4T/r39_Release_v2.0/release/Tegra_Linux_Sample-Root-Filesystem_R39.2.0_aarch64.tbz2

	echo "Unpack Jetson_Linux_R39.2.0_aarch64.tbz2"
	tar vxf Jetson_Linux_R39.2.0_aarch64.tbz2
	
	echo "Unpack Tegra_Linux_Sample-Root-Filesystem_R39.2.0_aarch64.tbz22"
	sudo tar vxpf Tegra_Linux_Sample-Root-Filesystem_R39.2.0_aarch64.tbz2 -C Linux_for_Tegra/rootfs/
		
	echo "Unpack Auvidea sources"
	tar vxf kernel_out.tar.xz -C ./Linux_for_Tegra/

	if [[ "$SOURCES" == "-s" ]]; then
		[ -f ./public_sources.tbz2 ] || wget https://developer.nvidia.com/downloads/embedded/L4T/r39_Release_v2.0/sources/public_sources.tbz2
		[ -f ./x-tools.tbz2 ] || wget https://developer.nvidia.com/downloads/embedded/L4T/r38_Release_v2.0/release/x-tools.tbz2
		echo "Unpack public_sources.tbz2"
		tar vxf public_sources.tbz2
		tar vxf x-tools.tbz2 -C Linux_for_Tegra/source/
		echo "Unpack kernel_src.tbz2"
		tar vxf Linux_for_Tegra/source/kernel_src.tbz2 -C Linux_for_Tegra/source/
		tar vxf Linux_for_Tegra/source/kernel_oot_modules_src.tbz2 -C Linux_for_Tegra/source/
		tar vxf Linux_for_Tegra/source/nvidia_kernel_display_driver_source.tbz2 -C Linux_for_Tegra/source/
		tar vxf Linux_for_Tegra/source/nvidia_unified_gpu_display_driver_source.tbz2 -C Linux_for_Tegra/source/

		echo "Unpack Auvidea source changes"
		tar xf kernel_src.tar.xz -C Linux_for_Tegra
		
		echo "Sources are prepared"
	fi

	cd Linux_for_Tegra/

	echo "run apply_binaries.sh"
	sudo ./apply_binaries.sh --openrm
	sudo ./tools/l4t_flash_prerequisites.sh
	
	cd ..
	echo "Unpack auvidea rootfs changes"
	sudo tar vxpf auvidea_rootfs.tar.gz -C Linux_for_Tegra/rootfs/
		
	echo "System is read to flash"

fi
exit 0

