#!/bin/bash
DOWNLOAD="aria2c -c --download-result=hide --console-log-level=error --disable-ipv6=true --summary-interval=0 --show-files=false"

source_dir (){
mkdir -p ${SRC}
cp -f board.txt ${SRC}/
cd ${SRC}
}

download (){
RPIURL="https://github.com/raspberrypi/linux/archive/"
echo ""
if [[ -f "${CKERNEL}-${COMMIT}.tar.gz" ]]; then
	:;
else
	echo -e "${WHT}Downloading ${CKERNEL}-${COMMIT}${FIN} ..."
	${DOWNLOAD} ${RPIURL}${COMMIT}.tar.gz
	echo -e " ${PNK}[${FIN}${GRN}done${FIN}${PNK}]${FIN}"
fi
}

report_tarball_error (){
echo "NOTICE: Tarball ${CKERNEL}-${COMMIT} is MIA. Please make a report."
echo ""
exit 0
}

extract (){
echo ""
if [[ -f "${CKERNEL}-${COMMIT}.tar.gz" ]]; then
	echo_extract
	pv ${CKERNEL}-${COMMIT}.tar.gz | tar -xzf - -C .
else
	report_tarball_error
fi
}

report_dir_error (){
echo "NOTICE: Directory ${CKERNEL}-${COMMIT} is MIA. Please make a report."
echo ""
exit 0
}

setup (){
if [[ -d "${CKERNEL}-${COMMIT}" ]]; then
	cd ${CKERNEL}-${COMMIT}
	export ARCH=${ARCH}
	if [[ "ARCH" == "arm" ]]; then KERNEL=${KERNEL_VAR}; fi
else
	report_dir_error
fi
}

cconfig (){
echo_cconfig
if [[ -f "../../defconfig/${MYCONFIG}" ]]; then
	cp -f ../../defconfig/${MYCONFIG} arch/${ARCH}/configs/
else
	echo ""
	echo -e "${MYCONFIG} was not found."
	echo -e "Check that the name is correct and in the correct location."
	echo -e "If you believe you are receiving this in error, please report it."
	read -p "Press enter to continue."
	exit 1
fi
kbuild "${MYCONFIG}"
echo ""
}

fconfig (){
echo -e "${WHT}Making ${LINUX_DEFCONFIG}${FIN}."
linux_configs
kbuild "${LINUX_DEFCONFIG}"
echo ""
}

save_defconfig (){
if [[ -f "defconfig" ]]; then
	echo ""
	mkdir -p ../../$OUTPUT/
	# minimal
	cp -f defconfig ../../$OUTPUT/${BOARD}_defconfig
	# full
	cp -f .config ../../$OUTPUT/${BOARD}-config_defconfig
	# path to files
	ls -ls ../../$OUTPUT/${BOARD}_defconfig | sed 's/..\/..\///g'
	ls -ls ../../$OUTPUT/${BOARD}-config_defconfig | sed 's/..\/..\///g'
fi
}

menuconfig (){
echo ""
echo_menuconfig
sleep .50
kbuild "menuconfig"
sleep .25
kbuild "savedefconfig"
echo "# ${BOARD} defconfig saved."
options=("Continue" "Quit")
select opt in "${options[@]}"
do
	case $opt in
		"Continue")
			save_defconfig
			break
			;;
		"Quit")
			save_defconfig
			exit 0
			;;
		*) echo "invalid option $REPLY";;
	esac
done
}

builddeb (){
if [ $CROSSCOMPILE -eq 1 ]; then echo -e "${GRN}  CC${FIN}      ${CROSS_COMPILE}${COMPILER}"; else echo -e "${GRN}  NC${FIN}      ${COMPILER}"; fi
echo ${BUILD_VERSION} > .version
echo 'y' | kbuild "LOCALVERSION= KBUILD_BUILD_USER=${KBUSER} KBUILD_BUILD_HOST=${KBHOST} bindeb-pkg"
}
