#!/bin/bash
source lib/function/echoes
source lib/source
validation
source lib/function/release
source custom.txt
source lib/function/staging
source lib/function/shrink
sleep 1
source userdata.txt
if [[ "$USERNAME" == "root" ]]; then
	echo -e "The username $USERNAME is not viable, choose another."
	echo -e ""
	read -p "Press enter to continue."
	exit 0
fi
# check user data file
if [ $USERACCT -eq 0 ]; then
	# prevent build fail because of white spaces
	NAME_FIXUP=`echo ${NAME} | sed "s/ //g"`
	if [ -z $NAME_FIXUP ] && [ -z $USERNAME ] && [ -z $PASSWORD ]; then
		echo -e ""
		echo -e "Name, Username and Password fields are empty?"
		echo -e "Enable the user account service or input your"
		echo -e "information into the userdata.txt file."
		echo -e ""
		read -p "Press enter to continue."
		exit 0
	fi
fi
source lib/function/miscellaneous
# start uscripts
if [ $USCRIPTS -eq 1 ]; then uscripts_pre-stage1; fi
if [[ -f "board.txt" ]]; then . board.txt; else noboard; fi
# clean
if [[ -d "sysroot" ]] || [[ -d "p1" ]] || [[ -d "BOOT" ]] || [[ -f "shrink.img" ]]; then make clean; clear -x; fi
# verbosity
if [ $VERBOSE -eq 1 ]; then set -eux -o pipefail; else set -eu -o pipefail; fi
mirrors
# check output
if [[ -d "output/${BOARD}" ]] && [[ `ls output/${BOARD}/linux-*.deb` ]]; then
	:;
else
	echo -e "Missing linux deb packages"
	exit 0
fi
# check for qemu
if [[ `command -v ${STATIC}` ]]; then
	:;
else
	echo -e "Missing depends: ${STATIC}"
	echo -e "Run ./install.sh"
	exit 1
fi

CAP_DISTRO=`echo "${DISTRO}" | sed -e "s/\b\(.\)/\u\1/g"`
CAP_RELEASE=`echo "${DISTRO_VERSION}" | sed -e "s/\b\(.\)/\u\1/g"`
echo ""
echo -e "${WHT}Board${FIN} ${PNK}[${FIN}${GRN}${BOARD}-${BOARD_EXT}${FIN}${PNK}]${FIN}"
echo -e "${WHT}Distribution${FIN} ${PNK}[${FIN}${GRN}${CAP_DISTRO} ${CAP_RELEASE}${FIN}${PNK}]${FIN}"
RAM=0
PROXY=""
IMAGE_FOLDER="img/"
IMAGE_DATE="$(date +%F)"
IMAGE_FILE_NAME="${BOARD_EXT}-${DISTRO}-${DISTRO_VERSION}-${IMAGE_DATE}.img"
if [ $RAM -ne 0 ]; then IMAGE_FOLDER="ram/"; fi
mkdir -p "$IMAGE_FOLDER"
if [ $RAM -ne 0 ]; then mount -t tmpfs -o size=4G tmpfs $IMAGE_FOLDER; fi
if [ $VERBOSE -eq 1 ]; then partition; uuid; else partition > /dev/null 2>&1; uuid > /dev/null 2>&1; fi
# command line
cmdline > /dev/null 2>&1
if [[ -f "p1/cmdline.txt" ]]; then
	:;
else
	echo -en "${WHT}cmdline.txt${FIN}  "
	sleep .50
	echo_fail
	exit 0
fi
# config dot txt
config_dot_txt > /dev/null 2>&1
if [[ -f "p1/config.txt" ]]; then
	:;
else
	echo ""
	echo -en "${WHT}config.txt${FIN}   "
	sleep .50
	echo_fail
	exit 0
fi
if [[ "$ARCH" == "arm" ]]; then sed -i '1d' p1/config.txt; fi

# extract rootfs
if [[ -f "${DISTRO}-${DISTRO_VERSION}-${ROOTFS_ARCH}.tar.xz" ]]; then
	echo -en "${WHT}Extracting rootfs${FIN} "
	tar -xf ${DISTRO}-${DISTRO_VERSION}-${ROOTFS_ARCH}.tar.xz -C ${P_VALUE}/
	echo_bdone
else
	echo -e "${YLW}Missing rootfs tarball${FIN}!"
	make cleanup
	exit 0
fi
echo ""

mkdir -p p2/etc/apt/apt.conf.d p2/etc/dpkg/dpkg.cfg.d
echo "force-unsafe-io" > "p2/etc/dpkg/dpkg.cfg.d/dpkg-unsafe-io"

# qemu static
mkdir -p p2/usr/bin
cp $(command -v "${STATIC}") p2/usr/bin

if [[ ! -z $P_VALUE ]]; then SOURCES_LIST="${P_VALUE}/etc/apt/sources.list"; fi
if [ $VERBOSE -eq 1 ]; then choose_release; fstab; else choose_release > /dev/null 2>&1; fstab > /dev/null 2>&1; fi

if [ -n "$PROXY" ] ; then
	tee "p2/etc/apt/apt.conf.d/30proxy" <<EOF
Acquire::http::proxy "http://127.0.0.1:3142";
EOF
fi

# setup stage2
cp scripts/stage2 p2/root
cp lib/function/services p2/root/services.txt
cp lib/function/miscellaneous p2/root/miscellaneous.txt
cp lib/function/networking p2/root/networking.txt
cp lib/source p2/root/source.txt
cp userdata.txt p2/root
cp board.txt p2/root
cp custom.txt p2/root
if [[ "$DISTRO" == "devuan" ]]; then
	cp files/inits/* p2/root
fi
cp files/patches/* p2/root
cp files/misc/* p2/root
cp files/scripts/* p2/root
cp files/users/* p2/root
cp files/firmware/* p2/root
if [ $USERACCT -eq 1 ]; then
	mkdir -p p2/root/useracct
	cp -r files/useracct/* p2/root/useracct
fi
if [ $USCRIPTS -eq 1 ]; then uscripts_stage1; fi
stage1_kernel # miscellaneous
echo -e "${WHT}Starting chroot${FIN} ..."
# Mount and chroot
mkdir -p p2/boot/broadcom
mount -o bind p1 p2/boot/broadcom
mount -o bind /dev p2/dev
mount -o bind /dev/pts p2/dev/pts
chroot p2 /root/stage2
# unmount
umount p2/dev/pts
umount p2/dev
umount p2/boot/broadcom
# clean
if [ -e p2/usr/bin/${STATIC} ]; then rm -f p2/usr/bin/${STATIC}; fi
cp -f p2/root/kernel.release .
rm p2/root/stage2
rm -f p2/root/{*.txt,kernel.release}
rm -fdr p2/var/cache/debconf/*
# finish uscripts
if [ $USCRIPTS -eq 1 ]; then uscripts_fin-stage1; fi
if [ -n "$PROXY" ]; then rm p2/etc/apt/apt.conf.d/30proxy; fi
rm p2/etc/dpkg/dpkg.cfg.d/dpkg-unsafe-io
if [[ -f "kernel.release" ]]; then source kernel.release; fi

# Finish
if [[ "$FSTYPE" == "ext4" ]]; then e4defrag -c ${P_VALUE}; fi
if [[ "$FSTYPE" == "btrfs" ]]; then btrfs filesystem defragment -f -r ${P_VALUE} > /dev/null 2>&1; fi
if [[ "$FSTYPE" == "xfs" ]]; then xfs_fsr ${P_VALUE}; fi
umount p2
umount p1
losetup -d "${IMAGE_LOOP_DEV}"
mv "${IMAGE_FOLDER}${IMAGE_FILE_NAME}" "${IMAGE_FILE_NAME}"
if [ $RAM -ne 0 ]; then umount "${IMAGE_FOLDER}"; fi
rmdir "${IMAGE_FOLDER}"
rmdir p1 p2

if [[ "$SHRINK" == "true" ]]; then shrink; fi
finish_image
rm -f {part-uuid.txt,board.txt,kernel.release}

exit 0
