#!/bin/bash
source lib/function/echoes
source lib/source
validation
if [[ -f "board.txt" ]]; then . board.txt; else noboard; fi
source kernel.txt
source userdata.txt
if [ $VERBOSE -eq 1 ]; then set -x; fi
source packaging/pkgvars
source lib/function/rpi-commit
source lib/function/patching
source lib/function/defconfig
source lib/function/compilers

# prep
validation
if [[ "$HOST_ARCH" == "aarch64" ]] && [[ "$ARCH" == "arm64" ]]; then CROSSCOMPILE="0"; fi
if [[ "$HOST_ARCH" == "aarch64" ]] && [[ "$ARCH" == "arm" ]]; then CROSSCOMPILE="1"; fi
if [[ "$HOST_ARCH" == "x86_64"  ]] && [[ "$ARCH" == "arm" || "$ARCH" == "arm64" ]]; then CROSSCOMPILE="1"; fi
# compiler
linux_compilers
# source directory
source_dir
# commit
if [ $ENABLE_COMMIT -eq 1 ]; then
	echo ""
	echo -e "${WHT}Using commit: ${FIN}${COMMIT}"
else
	echo ""
	echo -en "${WHT}Paste commit: ${FIN}"
	read COMMIT
fi

if [[ -e "${CKERNEL}-${COMMIT}" ]]; then
	echo ""
	echo -en "${WHT}${CKERNEL}-${COMMIT}${FIN}"
	echo -en " ${PNK}[${FIN}${YLW}removing${FIN}${PNK}]${FIN}"
	rm -fdr ${CKERNEL}-${COMMIT}
	echo -en " ${PNK}[${FIN}${GRN}done${FIN}${PNK}]${FIN}"
fi
# download
if [[ `wget -S --spider https://github.com/raspberrypi/linux/archive/${COMMIT}.tar.gz 2>&1 | grep 'HTTP/1.1 200 OK'` ]]; then
	download
else
	echo ""
	echo -e "${WHT}It appears the commit you selected is not available${FIN}?"
	exit 0
fi
# extract
extract
# setup and firmware
setup
firmware
# patching and packaging
linux_patching
# defconfig
if [ $CUSTOM_DEFCONFIG -eq 1 ]; then cconfig; else fconfig; fi
# menuconfig
if [ $MENUCONFIG -eq 1 ]; then menuconfig; fi
# builddeb
builddeb
echo ""
# finish
cd ..
rm -f {*linux-image-dbg*.deb,linux-libc-dev*.deb,*.buildinfo,*.changes}
if [[ `ls *linux*.deb` ]] > /dev/null 2>&1; then
	if [[ `ls ../${OUTPUT}/*linux*.deb` ]] > /dev/null 2>&1; then
		mkdir -p ../${OUTPUT}/tmp
		mv -f ../${OUTPUT}/{*linux-image*.deb,*linux-headers*.deb} ../${OUTPUT}/tmp
	fi
	mkdir -p ../${OUTPUT}
	mv -f *.deb ../${OUTPUT}/
	echo_done
	exit 0
else
	echo ""
	echo -e "${CKERNEL}-${COMMIT} [FAILED]"
	read -p "Press enter to continue."
	exit 1
fi

exit 0
