#!/usr/bin/env bash
ISO_NAME=${ISO_NAME:-arshit}
FS_ROOT=${FS_ROOT:-$ISO_NAME\_root}
VOLID=${VOLID:-$(echo "${ISO_NAME^^}" | cut -c-12)}
CHROOT_COMMAND=${CHROOT_COMMAND:-$(command -v arch-chroot || command -v artix-chroot || command -v chroot)}
USES_CHROOT="$(
	[[ "$CHROOT_COMMAND" == "$(command -v chroot)" ]]
	echo $((-$? + 1))
)"

print_help() {
	cat << EOF
Usage: $0 extract|unsquashfs|mount|umount|mksquashfs|build|update|cleanup
Usage: $0 chroot [program [arguments]]

Subcommands:
        extract         - Extract the ISO to a directory
        unsquashfs      - Extract the filesystem
        mount           - Mount the filesystem to /tmp/\$FS_ROOT
        chroot          - Chroot into the filesystem
        umount          - Unmount the filesystem
        mksquashfs      - Build the filesystem image
        build           - Build the ISO
        update          - Does all above while updating the system
        cleanup         - Removes work directories
EOF
}

case "$1" in
extract)

	mkdir -p "$ISO_NAME"
	bsdtar -C "$ISO_NAME" -xf "$ISO_NAME".iso
	sudo chmod -R +w "$ISO_NAME"

	;;
unsquashfs)

	[ -e "$FS_ROOT" ] && sudo rm -rf "$FS_ROOT"
	sudo unsquashfs -d "$FS_ROOT" "$ISO_NAME"/LiveOS/rootfs.img

	;;
mount)

	mkdir -p "/tmp/$FS_ROOT"
	sudo mount --bind "$FS_ROOT" "/tmp/$FS_ROOT"
	if [[ "$USES_CHROOT" == 1 ]]; then
		sudo mount --bind /dev "/tmp/$FS_ROOT"/dev
		sudo mount --bind /sys "/tmp/$FS_ROOT"/sys
		sudo mount --bind /proc "/tmp/$FS_ROOT"/proc
	fi

	;;
chroot)

	# shellcheck disable=SC2086,SC2068
	sudo $CHROOT_COMMAND "/tmp/$FS_ROOT" ${@:2}
	
	;;
umount)

	if [[ "$USES_CHROOT" == 1 ]]; then
		sudo umount /tmp/"$FS_ROOT"/dev
		sudo umount "/tmp/$FS_ROOT"/sys
		sudo umount "/tmp/$FS_ROOT"/proc
	fi
	sudo umount "/tmp/$FS_ROOT"
	rm -r "/tmp/$FS_ROOT"

	;;
mksquashfs)

	sudo mksquashfs "$FS_ROOT" "$ISO_NAME/LiveOS/rootfs.img" -comp zstd -noappend
	[[ "$MD5SUM" == 1 ]] && md5sum "$ISO_NAME"/LiveOS/rootfs.img > \
		"$ISO_NAME"/LiveOS/rootfs.img.md5

	;;
build)

	perl -pe 's/(?<=label=)[A-Z0-9_]{0,32}(?= |;)/'"$VOLID"'/' <"$ISO_NAME"/boot/grub/kernels.cfg |
		sponge "$ISO_NAME"/boot/grub/kernels.cfg

	sudo xorriso -as mkisofs \
		-volid "$VOLID" \
		--protective-msdos-label -r \
		-graft-points -no-pad \
		--sort-weight 0 / --sort-weight 1 /boot \
		--grub2-mbr "$ISO_NAME"/boot/grub/i386-pc/boot_hybrid.img \
		-b boot/grub/i386-pc/eltorito.img -c boot.catalog \
		-no-emul-boot -boot-load-size 4 \
		-boot-info-table --grub2-boot-info -eltorito-alt-boot \
		-append_partition 2 0xef "$ISO_NAME"/boot/efi.img -no-emul-boot \
		-iso-level 3 \
		-o "$ISO_NAME".iso "$ISO_NAME"

	;;
cleanup)

	rm -rf "$ISO_NAME"
	sudo rm -rf "$FS_ROOT"

	;;
update)

	$0 extract
	$0 unsquashfs
	$0 mount
	if $0 chroot [ ! -e /etc/pacman.d/gnupg/trustdb.gpg ]; then
		$0 chroot pacman-key --init
		$0 chroot pacman-key --populate artix
		# Fetch key from wiki
		# shellcheck disable=SC2046
		$0 chroot $(curl https://wiki.artixlinux.org/Main/Migration | grep -oP 'pacman-key --lsign-key [0-9A-F]{40}')
	fi
	$0 chroot pacman -Syu --noconfirm
	$0 umount
	$0 mksquashfs
	$0 build
	$0 cleanup

	;;
*)

	print_help
	exit 1

	;;
esac
exit $?