#!/bin/bash

# stage 1
stage1_kernel (){
if [[ `ls ${OUTPUT}/{linux-image-*.deb,linux-headers-*.deb}` ]] > /dev/null 2>&1; then
	cp ${OUTPUT}/*.deb p2/root
else
	echo ""
	echo -en "${BOARD}"
	echo -e ": Compile a kernel before building an image."
	make cleanup
	exit 1
fi
}

# stage 2
raspberrypi_sys_mods (){
echo ""
echo "Installing raspi-sys-mods ..."
git clone https://github.com/RPi-Distro/raspberrypi-sys-mods.git
if [[ "$DISTRO" == "devuan" ]]; then
	mv -f raspberrypi-sys-mods-control.patch raspberrypi-sys-mods/
	cd raspberrypi-sys-mods
	git checkout -q 46ae4208397d662fc4f5d0cc9acc85395f852af1
	patch -p1 < raspberrypi-sys-mods-control.patch
	rm -f raspberrypi-sys-mods-control.patch
else
	rm -f raspberrypi-sys-mods-control.patch
	cd raspberrypi-sys-mods
	git checkout -q 46ae4208397d662fc4f5d0cc9acc85395f852af1
fi
dpkg-buildpackage -us -uc
cd ~
dpkg -i raspberrypi-sys-mods*.deb
rm -fdr raspberrypi-sys-mods*
rm -f /etc/apt/sources.list.d/vscode.list
rm -f /etc/apt/trusted.gpg.d/microsoft.gpg
rm -f /etc/apt/preferences.d/3rd_parties.pref
}

# rpi-eeprom
find_eeprom (){
EEPROM_VERSION=$(curl --silent -L ${CHANGELOG} | awk '{if (NR==1) {print substr($2, 1, length($2)-3)}}' | sed 's/[()]//g')
if [[ `wget -S --spider ${ERURL}rpi-eeprom_${EEPROM_VERSION}.orig.tar.gz 2>&1 | grep 'HTTP/1.1 200 OK'` ]]; then
	download_eeprom
else
	finding_eeprom
fi
}

finding_eeprom (){
EEPROM_VERSION=$(curl --silent -L ${CHANGELOG} | awk '{if (NR==10) {print substr($2, 1, length($2)-3)}}' | sed 's/[()]//g')
if [[ `wget -S --spider ${ERURL}rpi-eeprom_${EEPROM_VERSION}.orig.tar.gz 2>&1 | grep 'HTTP/1.1 200 OK'` ]]; then
	download_eeprom
else
	EEPROM_VERSION="20.1"
	download_eeprom
fi
}

download_eeprom (){
wget -cq --show-progress ${ERURL}rpi-eeprom_${EEPROM_VERSION}-1.debian.tar.xz
wget -cq --show-progress ${ERURL}rpi-eeprom_${EEPROM_VERSION}.orig.tar.gz
}

eeprom_support (){
ERURL="https://archive.raspberrypi.org/debian/pool/main/r/rpi-eeprom/"
CHANGELOG="https://raw.githubusercontent.com/raspberrypi/rpi-eeprom/debian/bookworm/debian/changelog"
echo ""
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
echo "Installing rpi-eeprom ..."
apt install help2man rsync pciutils -y
mkdir -p ~/eeprom
mv -f rpi-eeprom-update.patch /root/eeprom/
mv -f rpi-eeprom-control /root/eeprom/
cd ~/eeprom
find_eeprom
tar xf rpi-eeprom_${EEPROM_VERSION}.orig.tar.gz
tar xf rpi-eeprom_${EEPROM_VERSION}-1.debian.tar.xz
rm -f rpi-eeprom_${EEPROM_VERSION}-1.debian.tar.xz
mkdir -p debian/patches
mv rpi-eeprom-update.patch debian/patches/rpi-eeprom-update.patch 
echo rpi-eeprom-update.patch >> debian/patches/series
rm -f debian/control; mv -f rpi-eeprom-control debian/control
mv -f debian rpi-eeprom-${EEPROM_VERSION}/
cd rpi-eeprom-${EEPROM_VERSION}
rm -f rpi-eeprom-control.patch
dpkg-buildpackage -us -nc -uc
cd ..
dpkg -i *.deb
cd ..
rm -fdr eeprom
}

# userland
rpi_userland (){
echo ""
echo "Installing userland ..."
rm -f /etc/profile
mv -f profile /etc/profile
mv rpi-vc.conf /etc/ld.so.conf.d/rpi-vc.conf
chown root:root /etc/profile
chown root:root /etc/ld.so.conf.d/rpi-vc.conf
mkdir -p /opt
git clone https://github.com/raspberrypi/userland.git
mv -f userland-remove-hi-pi.patch /root/userland/
cd userland
patch -p1 < userland-remove-hi-pi.patch
rm -f userland-remove-hi-pi.patch
if [[ "$ARCH" == "arm64" ]]; then
	echo -e "\e[1;37m== ARM64\e[0m"
	sleep .50
	./buildme --aarch64
else
	echo -e "\e[1;37m== ARM\e[0m"
	sleep .50
	./buildme
fi
cd ~
rm -fdr userland
ldconfig
}

# modules
bcm_modules (){
rm -f /etc/modules
tee /etc/modules <<EOF
# /etc/modules: kernel modules to load at boot time.
#
# This file contains the names of kernel modules that should be loaded
# at boot time, one per line. Lines beginning with "#" are ignored.
#bcm2835-v4l2
#i2c-dev

EOF
chown root:root /etc/modules
}

# linux kernel
stage2_kernel (){
echo ""
echo "Installing kernel ..."
apt update
apt upgrade -y
apt -y clean
apt -y autoclean
sleep 1s
cd ~
dpkg -i *.deb
rm -f *.deb
sleep .75
# take note of linux kernel release
if [ -f /usr/src/linux-headers-*/include/config/kernel.release ]; then
	KERNEL_RELEASE=`cat /usr/src/linux-headers-*/include/config/kernel.release`
else
	KERNEL_RELEASE=`ls /boot/config-* | sed 's/\/boot\/config-//g'`
fi
echo -e INSTALLED_KERNEL='"'$KERNEL_RELEASE'"' > /root/kernel.release
# add fstype to the board.txt and kernel.release file
echo FSTYPE='"'${FSTYPE}'"' >> /root/kernel.release
echo "" >> /etc/opt/board.txt
echo "# filesystem" >> /etc/opt/board.txt
echo FSTYPE='"'${FSTYPE}'"' >> /etc/opt/board.txt
}

# whiptail color palette (ubuntu)
palette-dark (){
tee /etc/newt/palette.dark <<EOF
root=,black
checkbox=,black
entry=,black
label=black,
actlistbox=,black
helpline=,black
roottext=lightgray,black
emptyscale=black
disabledentry=black,
EOF
}

xorg_confs (){
mkdir -p /etc/X11/xorg.conf.d
cat <<EOF > "/etc/X11/xorg.conf.d/99-v3d.conf"
Section "OutputClass"
  Identifier "vc4"
  MatchDriver "vc4"
  Driver "modesetting"
  Option "PrimaryGPU" "true"
EndSection
EOF
}

# user scripts
uscripts_pre-stage1 (){
if [[ -f "files/userscripts/uscripts" ]]; then
	source files/userscripts/uscripts
	if [[ `type run_function0` ]] &>/dev/null; then run_function0; fi
fi
}

uscripts_stage1 (){
if [[ -f "files/userscripts/uscripts" ]]; then
	mkdir -p p2/root/userscripts
	cp -fr files/userscripts/* p2/root/userscripts/
	if [[ -f "p2/root/userscripts/README.md" ]]; then rm -f p2/root/userscripts/README.md; fi
	if [[ `type run_function1` ]] &>/dev/null; then run_function1; fi
fi
}

uscripts_stage2 (){
if [[ -f "/root/userscripts/uscripts" ]]; then
	source /root/userscripts/uscripts
	if [[ `type run_function2` ]] &>/dev/null; then
		echo ""
		echo -e "\033[1mRunning user scripts\e[0m ..."
		run_function2
		echo -e "\033[1mDone\e[0m."
	fi
fi
if [[ -e "/root/userscripts" ]]; then rm -fdr /root/userscripts; fi
}

uscripts_fin-stage1 (){
if [[ -f "files/userscripts/uscripts" ]]; then
	source files/userscripts/uscripts
	if [[ `type run_function3` ]] &>/dev/null; then run_function3; fi
fi
}

# ubuntu apt preferences
apt_preferences (){
CAP_DISTRO=`echo "${DISTRO}" | sed -e "s/\b\(.\)/\u\1/g"`
echo
echo Blacking listing packages.
tee /etc/apt/preferences <<EOF
Package: rpi-eeprom linux-firmware linux-firmware-raspi2 pi-bluetooth raspberrypi-sys-mods
Pin: release o=${CAP_DISTRO}
Pin-Priority: 1
EOF
echo Done.
}

# fin and compress
finish_image (){
IMAGE_TIME="$(date +%T | sed 's/://g' | sed 's/..$//')"
IMAGE_FIN_NAME="${BOARD_EXT}-${DISTRO}-${DISTRO_VERSION}-${INSTALLED_KERNEL}-${ARCH_EXT}-${FSTYPE}-${IMAGE_DATE}-${IMAGE_TIME}.img"
if [[ -f "${IMAGE_FILE_NAME}" ]]; then
	mv -f ${IMAGE_FILE_NAME} ${IMAGE_FIN_NAME}
else
	echo -e "Build error: ${IMAGE_FILE_NAME}"
	exit 1
fi
if [ $COMPRESS_IMG -eq 1 ]; then
	if [[ -f "${IMAGE_FIN_NAME}" ]]; then
		echo -e ""
		echo_compress
		xz -zev --threads=${CORES} ${IMAGE_FIN_NAME}
		if [[ -f "${IMAGE_FIN_NAME}.xz" ]]; then
			sha256sum ${IMAGE_FIN_NAME}.xz > ${IMAGE_FIN_NAME}.xz.sha256
			sha256sum --check ${IMAGE_FIN_NAME}.xz.sha256
		fi
	else
		echo -e ""
		echo -e "${IMAGE_FIN_NAME} not found?"
	fi
fi
}
