#!/usr/bin/env bash

# =============================================================================
# AVASILE - Argent Vasile
# Versatile Advanced Script for ISOs and Latest Enhancements
# Copyright (C) 2015 Ghiunhan Mamut (nicknamed V3n3RiX) & Rogentos Team
# Copyright (C) 2025 Argent Team
# =============================================================================

# Import Gentoo functions
source /lib/gentoo/functions.sh

# =============================================================================
# CONFIGURATION VARIABLES
# =============================================================================

# Release Information
export releasename="argent"
export releasetarget="ws"
export releaseversion="1"

# Kernel Configuration
export kernelver="6.12.9-${releasename}"

# Core SquashFS Configuration
export chrootx64="${releasename}_${releasetarget}_${releaseversion}_core_x64.squashfs"
export chrootx64md5="${chrootx64}.md5"

# Overlay Mount Directories
export rodir="rodir"
export rwdir="rwdir"
export workdir="workdir"  # Required for overlayfs on kernel > 3.18
export overlaydir="overlaydir"

# Build Environment Variables
export chrootuser="root"
export chroot_target="${@:2}"
export chrootbuildtarget="emerge -kav ${chroot_target}"
export chrootsrcmode="avasile --srcmode"

# ISO Creation Variables
export isouser="root"
export isomainarch="x86_64"
export isobinmode="avasile --usermode"
export isokernelname="kernel-genkernel-${isomainarch}-${kernelver}"
export isoramfsname="initramfs-genkernel-${isomainarch}-${kernelver}"

# ISO Commands
export isoramfscmd="dracut -N -a dmsquash-live -a pollcdrom -a mdraid \
    -o systemd -o systemd-initrd -o systemd-networkd -o dracut-systemd \
    -o btrfs -o crypt -o i18n -o usrmount -o lunmask -o nvdimm -o multipath \
    -I busybox --force --kver ${kernelver} /boot/${isoramfsname}"

export isoeficmd="grub-mkimage -d /usr/lib/grub/x86_64-efi -o bootx64.efi \
    -O x86_64-efi ext2 fat udf btrfs ntfs reiserfs xfs hfsplus lvm ata \
    part_msdos part_gpt part_apple bsd search_fs_uuid normal chain iso9660 \
    configfile help loadenv reboot cat search memdisk tar boot linux chain \
    -p /boot/grub"

export isochainloadcmd="grub-mkimage -d /usr/lib/grub/i386-pc -o core.img \
    -O i386-pc biosdisk part_msdos fat -p /boot/grub"

# ISO Directory Layout
export BOOTLOADER_FETCH_PATH="/tmp/bootcore"
export BOOTLOADER_CONFIGS="${BOOTLOADER_FETCH_PATH}/cdroot/boot"
export ISO_ROOT_DIR="${releasename}-${releasetarget}-${releaseversion}-${isomainarch}"
export ISO_GRUB_DIR="${ISO_ROOT_DIR}/boot/grub"
export ISO_EFI_DIR="${ISO_ROOT_DIR}/efi/boot"
export ISO_RSYNC_TARGET="${ISO_ROOT_DIR}/rootfs"
export ISO_RSYNC_SOURCE="/tmp/${ISO_ROOT_DIR}"
export ISO_CDROOT_DIR="${ISO_ROOT_DIR}/CDroot"
export ISO_REALFS_DIR="${ISO_CDROOT_DIR}/LiveOS"
export ISO_SQUASHFS_DIR="${ISO_ROOT_DIR}/LiveOS"

# Repository and Configuration Paths
export PORTAGE_MAIN_DIR="/var/db/repos/gentoo"
export ARGENT_MAIN_DIR="${ARGENT_MAIN_DIR:-/var/db/repos/argent-ws}"
export PORTAGE_LINK_CONFDIR="/etc/portage"
export PORTAGE_GITDIR="${PORTAGE_GITDIR:-/opt/argentws-build/conf/intel/portage}"
export PORTAGE_MAIN_CONFDIR="${PORTAGE_MAIN_CONFDIR:-/opt/argentws-build}"
export PORTAGE_REPO="${PORTAGE_REPO:-https://gitlab.com/argent/argentws-build.git}"

# Feature Flags
export ARGENT_USE_SUDO="${ARGENT_USE_SUDO:-0}"

# =============================================================================
# CORE SYSTEM FUNCTIONS
# =============================================================================

kernelconfig() {
	# Check if host kernel has required modules for avasile
	local required_configs=(
		'CONFIG_OVERLAY_FS='
		'CONFIG_SQUASHFS='
		'CONFIG_BLK_DEV_LOOP='
	)
	
	local missing_configs=()
	for config in "${required_configs[@]}"; do
		if ! zgrep -q "${config}" /proc/config.gz; then
			missing_configs+=("${config}")
		fi
	done
	
	if [[ ${#missing_configs[@]} -eq 0 ]]; then
		einfo "Kernel configuration check passed"
		sleep 1
	else
		eerror "Vasile requires the following kernel modules:"
		for config in "${missing_configs[@]}"; do
			eerror "  - ${config}"
		done
		eerror "Please rebuild your kernel with these options enabled"
		exit 1
	fi
}

checkmode() {
	local avasile_mode
	avasile_mode=$(readlink -f /etc/portage/make.conf)
	
	case "${avasile_mode}" in
		"${PORTAGE_MAIN_CONFDIR}/conf/intel/portage/make.conf.amd64-user")
			echo "$0 is on --usermode"
			;;
		"${PORTAGE_MAIN_CONFDIR}/conf/intel/portage/make.conf.amd64-devel")
			echo "$0 is on --devmode!"
			;;
		"${PORTAGE_MAIN_CONFDIR}/conf/intel/portage/make.conf.amd64-srcmode")
			echo "$0 is on --srcmode!"
			;;
		"${PORTAGE_MAIN_CONFDIR}/conf/intel/portage/make.conf.amd64-custom")
			echo "$0 is on your own custom mode!"
			;;
		*)
			echo "$0 is not on any known modes"
			;;
	esac
}

checkroot() {
	# Verify root privileges for mount and chroot operations
	if [[ "${UID}" != "0" ]]; then
		eerror "Root privileges required for this operation"
		echo
		
		if command -v sudo >/dev/null 2>&1; then
			einfo "Attempting to restart with sudo..."
			sudo "$0" "$@"
		else
			eerror "sudo not available. Please run as root"
			exit 1
		fi
	fi
}

checkiflive() {
	# Prevent execution in live environment
	if [[ -L /dev/mapper/live-base ]]; then
		eerror "Running in Live mode is unsupported"
		exit 1
	fi
}

chrootchecksum() {
	# Verify core squashfs integrity
	while true; do
		if [[ -f "${chrootx64}" && -f "${chrootx64md5}" ]]; then
			einfo "Found squashed chroot and checksum file"
			
			if md5sum -c "${chrootx64md5}" >/dev/null 2>&1; then
				einfo "Squashed chroot checksum verification passed"
				sleep 1
				break
			else
				eerror "Squashed chroot checksum verification failed"
				exit 1
			fi
		else
			eerror "Missing squashed chroot or checksum file"
			eerror "Expected files: ${chrootx64}, ${chrootx64md5}"
			exit 1
		fi
	done
}

# =============================================================================
# CHROOT ENVIRONMENT MANAGEMENT
# =============================================================================

chrootprepare() {
	# Create fresh overlay mount environment
	local directories=("${rodir}" "${rwdir}" "${workdir}" "${overlaydir}")
	
	while true; do
		# Create required directories
		for dir in "${directories[@]}"; do
			if [[ ! -d "${dir}" ]]; then
				mkdir -p "${dir}"
			fi
		done
		
		# Verify all directories exist
		local all_exist=true
		for dir in "${directories[@]}"; do
			if [[ ! -d "${dir}" ]]; then
				all_exist=false
				break
			fi
		done
		
		if [[ "${all_exist}" == "true" ]]; then
			chrootstart
			break
		else
			einfo "Directory creation failed, cleaning up and retrying..."
			chrootstop
			for dir in "${directories[@]}"; do
				rm -rf "${dir}"
			done
			continue
		fi
	done
}

chrootstop() {
	# Unmount chroot overlay filesystem
	local mount_points=(
		"${overlaydir}/proc"
		"${overlaydir}/sys"
		"${overlaydir}/dev/pts"
		"${overlaydir}/dev/shm"
		"${overlaydir}/dev"
		"${overlaydir}/tmp"
		"${overlaydir}/var/cache/binpkgs"
		"${overlaydir}/var/cache/distfiles"
		"${overlaydir}"
		"${rodir}"
	)
	
	for mount_point in "${mount_points[@]}"; do
		umount -l "${mount_point}" >/dev/null 2>&1
	done
}

chrootstart() {
	# Mount core squashfs in overlay configuration
	mount -t squashfs "${chrootx64}" "${rodir}"
	mount -t overlay \
		-o lowerdir="${rodir}",upperdir="${rwdir}",workdir="${workdir}" \
		overlay "${overlaydir}"
	
	# Bind mount package and distfile caches
	mount -o bind packages "${overlaydir}/var/cache/binpkgs"
	mount -o bind distfiles "${overlaydir}/var/cache/distfiles"
	
	# Mount virtual filesystems
	mount -t proc proc "${overlaydir}/proc"
	mount -t sysfs sysfs "${overlaydir}/sys"
	mount -t devtmpfs \
		-o relatime,size=3055348k,nr_inodes=763837,mode=755 \
		none "${overlaydir}/dev"
	mount -t devpts \
		-o nosuid,noexec,relatime,gid=5,mode=620 \
		none "${overlaydir}/dev/pts"
	mount -t tmpfs \
		-o nosuid,nodev \
		none "${overlaydir}/dev/shm"
	mount -t tmpfs \
		-o nosuid,nodev,noexec \
		none "${overlaydir}/tmp"
}

chrootdevtree() {
	# Initialize portage tree and overlay in chroot
	chroot "${overlaydir}" su - "${chrootuser}" -c "${chrootsrcmode}"
}

chrootbuild() {
	# Build and install packages in chroot environment
	einfo "Starting package build process..."
	sleep 1
	chroot "${overlaydir}" su - "${chrootuser}" -c "${chrootbuildtarget}"
}

chrootx64_iso() {
	# Interactive chroot shell for build adjustments
	einfo "========================================"
	einfo "DROPPING YOU TO A ROOT SHELL"
	einfo "BUILD ENVIRONMENT READY"
	einfo "========================================"
	einfo "Available actions:"
	einfo "- Fix build failures"
	einfo "- Adjust portage configuration"
	einfo "- Test USE flags and keywords"
	einfo "- Commit your changes before exit"
	einfo "========================================"
	
	chroot "${overlaydir}" su - "${chrootuser}"
}

regenerate_cache() {
	env-update
	# shellcheck source=/dev/null
	. /etc/profile
}

makepkg() {
	# Main package building workflow
	checkroot
	chrootchecksum
	chrootprepare
	chrootdevtree
	chrootbuild
	chrootx64_iso
	chrootstop
}

# =============================================================================
# ISO CREATION FUNCTIONS
# =============================================================================

isostart() {
	# Mount ISO image core filesystems
	local mount_points=(
		"packages:${ISO_RSYNC_TARGET}/usr/portage/packages:bind"
		"proc:${ISO_RSYNC_TARGET}/proc:proc"
		"sysfs:${ISO_RSYNC_TARGET}/sys:sysfs"
		"devtmpfs:${ISO_RSYNC_TARGET}/dev:devtmpfs:-o relatime,size=3055348k,nr_inodes=763837,mode=755"
		"devpts:${ISO_RSYNC_TARGET}/dev/pts:devpts:-o nosuid,noexec,relatime,gid=5,mode=620"
		"tmpfs:${ISO_RSYNC_TARGET}/dev/shm:tmpfs:-o nosuid,nodev"
		"tmpfs:${ISO_RSYNC_TARGET}/tmp:tmpfs:-o nosuid,nodev,noexec"
	)
	
	for mount_spec in "${mount_points[@]}"; do
		IFS=':' read -r source target fstype options <<< "${mount_spec}"
		if [[ -n "${options}" ]]; then
			mount -t "${fstype}" ${options} none "${target}"
		elif [[ "${fstype}" == "bind" ]]; then
			mount -o bind "${source}" "${target}"
		else
			mount -t "${fstype}" "${fstype}" "${target}"
		fi
	done
}

isostop() {
	# Unmount ISO image core filesystems
	local mount_points=(
		"${ISO_RSYNC_TARGET}/proc"
		"${ISO_RSYNC_TARGET}/sys"
		"${ISO_RSYNC_TARGET}/dev/pts"
		"${ISO_RSYNC_TARGET}/dev/shm"
		"${ISO_RSYNC_TARGET}/dev"
		"${ISO_RSYNC_TARGET}/tmp"
		"${ISO_RSYNC_TARGET}/usr/portage/packages"
	)
	
	for mount_point in "${mount_points[@]}"; do
		umount -l "${mount_point}" >/dev/null 2>&1
	done
}

isousertree() {
	# Initialize portage tree and overlay in ISO environment
	chroot "${ISO_RSYNC_TARGET}" su - "${isouser}" -c "${isobinmode}"
}

isoramfs() {
	# Generate ISO initramfs with live boot modules
	chroot "${ISO_RSYNC_TARGET}" su - "${isouser}" -c "${isoramfscmd}"
}

isoefiimg() {
	# Generate EFI bootloader
	chroot "${ISO_RSYNC_TARGET}" su - "${isouser}" -c "${isoeficmd}"
}

isochainloader() {
	# Generate GRUB chainloader for unetbootin compatibility
	chroot "${ISO_RSYNC_TARGET}" su - "${isouser}" -c "${isochainloadcmd}"
}

isoservices() {
	# Enable live ISO system services
	set -x
	
	local services=(
		"argentlive"
		"argent-config-vbox"
		"avahi-daemon"
		"connman"
		"cups"
		"dkms"
		"dm-event"
		"lvm2-lvmetad"
		"lvm2-monitor"
		"NetworkManager"
		"ModemManager"
		"sddm"
		"virtualbox-guest-additions"
	)
	
	# Enable system services
	for service in "${services[@]}"; do
		chroot "${ISO_RSYNC_TARGET}" su - "${isouser}" -c "systemctl enable ${service}"
	done
	
	# Configure networking
	chroot "${ISO_RSYNC_TARGET}" su - "${isouser}" -c "rm -f /etc/resolv.conf"
	chroot "${ISO_RSYNC_TARGET}" su - "${isouser}" -c \
		"ln -s /run/systemd/resolve/stub-resolv.conf /etc/resolv.conf"
	
	# Configure audio services (disable PulseAudio, enable PipeWire)
	chroot "${ISO_RSYNC_TARGET}" su - "${isouser}" -c \
		"systemctl --user disable pulseaudio.socket pulseaudio.service"
	chroot "${ISO_RSYNC_TARGET}" su - "${isouser}" -c \
		"systemctl --user enable pipewire-pulse.socket wireplumber.service pipewire.service"
	
	set +x
}

isochroot() {
	# Interactive ISO environment setup
	einfo "========================================"
	einfo "ISO ENVIRONMENT SETUP"
	einfo "========================================"
	
	if [[ -z "${*:2}" ]]; then
		einfo "Interactive mode:"
		einfo "- Install apps and targets"
		einfo "- Configure desktop environment"
		einfo "- Exit when finished"
		einfo "========================================"
		
		chroot "${ISO_RSYNC_TARGET}" su - "${isouser}"
		chroot "${ISO_RSYNC_TARGET}" su - "${isouser}" -c "umount -f /mnt/argent_efipart/dev/* 2>/dev/null || true"
		chroot "${ISO_RSYNC_TARGET}" su - "${isouser}" -c "env-update"
	else
		einfo "Automated installation mode"
		einfo "Installing packages from provided lists..."
		
		# Clean up previous package list
		if [[ -e "${ISO_RSYNC_TARGET}/ISO_Installed_Packages" ]]; then
			rm -f "${ISO_RSYNC_TARGET}/ISO_Installed_Packages"
		fi
		
		# Combine all package lists
		for package_list in "${@:2}"; do
			if [[ -f "${package_list}" ]]; then
				cat "${package_list}" >> "${ISO_RSYNC_TARGET}/ISO_Installed_Packages"
			else
				ewarn "Package list not found: ${package_list}"
			fi
		done
		
		if [[ -f "${ISO_RSYNC_TARGET}/ISO_Installed_Packages" ]]; then
			mapfile -t iso_packages < "${ISO_RSYNC_TARGET}/ISO_Installed_Packages"
			
			if [[ ${#iso_packages[@]} -gt 0 ]]; then
				einfo "Installing ${#iso_packages[@]} packages..."
				chroot "${ISO_RSYNC_TARGET}" su - "${isouser}" -c "epkg autoinstall ${iso_packages[*]}"
			else
				ewarn "No packages found in provided lists"
			fi
		fi
		
		# Cleanup
		chroot "${ISO_RSYNC_TARGET}" su - "${isouser}" -c "umount -f /mnt/argent_efipart/dev/* 2>/dev/null || true"
		chroot "${ISO_RSYNC_TARGET}" su - "${isouser}" -c "env-update"
	fi
}

prepareiso() {
	# Prepare ISO image layout and filesystem
	einfo "========================================"
	einfo "PREPARING ISO IMAGE LAYOUT"
	einfo "========================================"
	
	# Create directory structure
	local iso_directories=(
		"${ISO_RSYNC_TARGET}"
		"${ISO_RSYNC_SOURCE}"
		"${ISO_CDROOT_DIR}"
		"${ISO_SQUASHFS_DIR}"
		"${ISO_REALFS_DIR}"
		"${ISO_GRUB_DIR}"
		"${ISO_EFI_DIR}"
	)
	
	for dir in "${iso_directories[@]}"; do
		mkdir -p "${dir}"
	done
	
	# Create base filesystem image
	einfo "Creating base filesystem image (20GB)..."
	dd if=/dev/zero of="${ISO_RSYNC_TARGET}.img" bs=50M count=400 status=progress
	mkfs.ext4 -F "${ISO_RSYNC_TARGET}.img"

	# Mount and sync core squashfs contents
	einfo "Mounting core squashfs and syncing contents..."
	mount -t squashfs "${chrootx64}" "${ISO_RSYNC_SOURCE}"
	mount -t ext4 "${ISO_RSYNC_TARGET}.img" "${ISO_RSYNC_TARGET}"

	einfo "Syncing filesystem contents..."
	if rsync -aHAXr "${ISO_RSYNC_SOURCE}/" "${ISO_RSYNC_TARGET}/"; then
		einfo "Filesystem sync completed successfully"
	else
		eerror "Failed to sync filesystem contents"
		exit 1
	fi
	
	# Handle kernel for live boot
	einfo "Preparing kernel for live boot..."
	if [[ ! -f "${ISO_RSYNC_TARGET}/boot/${isokernelname}" ]]; then
		ewarn "Kernel not found, generating with dracut..."
		dracut -H -f \
			-o systemd -o systemd-initrd -o systemd-networkd \
			-o dracut-systemd -o plymouth \
			--early-microcode --kver="${kernelver}" \
			"${ISO_RSYNC_TARGET}/boot/${isokernelname}"
		
		if [[ -f "${ISO_RSYNC_TARGET}/boot/${isokernelname}" ]]; then
			cp -avx "${ISO_RSYNC_TARGET}/boot/${isokernelname}" "${ISO_ROOT_DIR}/boot/vmlinuz"
		else
			eerror "Failed to generate kernel"
			exit 1
		fi
	else
		einfo "Using existing kernel..."
		cp -avx "${ISO_RSYNC_TARGET}/boot/${isokernelname}" "${ISO_ROOT_DIR}/boot/vmlinuz"
	fi
	
	# Generate initramfs
	einfo "Generating initramfs for live boot..."
	isostart
	isoramfs
	isostop
	
	if [[ -f "${ISO_RSYNC_TARGET}/boot/${isoramfsname}" ]]; then
		einfo "Moving initramfs to final location..."
		mv "${ISO_RSYNC_TARGET}/boot/${isoramfsname}" "${ISO_ROOT_DIR}/boot/initrd"
	else
		eerror "Failed to generate initramfs"
		exit 1
	fi
	
	# Generate EFI bootloader
	einfo "Generating EFI bootloader..."
	isostart
	isoefiimg
	isostop
	
	if [[ -e "${ISO_RSYNC_TARGET}/root/bootx64.efi" ]]; then
		mv "${ISO_RSYNC_TARGET}/root/bootx64.efi" "${ISO_EFI_DIR}/"
		chmod 755 "${ISO_EFI_DIR}/bootx64.efi"
		einfo "EFI bootloader installed successfully"
	else
		ewarn "EFI bootloader not generated - you may need to create it manually"
	fi
	
	# Generate GRUB chainloader for unetbootin compatibility
	einfo "Generating GRUB chainloader..."
	isostart
	isochainloader
	isostop
	
	if [[ -e "${ISO_RSYNC_TARGET}/root/core.img" ]]; then
		mv "${ISO_RSYNC_TARGET}/root/core.img" "${ISO_GRUB_DIR}/"
		einfo "GRUB chainloader installed successfully"
	else
		ewarn "GRUB chainloader not generated - you may need to create it manually"
	fi
	
	# Copy additional GRUB files
	if [[ -e "${ISO_RSYNC_TARGET}/usr/lib/grub/i386-pc/lnxboot.img" ]]; then
		cp -avx "${ISO_RSYNC_TARGET}/usr/lib/grub/i386-pc/lnxboot.img" "${ISO_GRUB_DIR}/"
	else
		ewarn "lnxboot.img not found - some boot features may not work"
	fi
	
	# Configure live ISO environment
	einfo "Configuring live ISO system services..."
	isostart
	isousertree
	isochroot "$@"
	isostop
	
	isostart
	isoservices
	isostop
	
	# Finalize filesystem
	einfo "Finalizing ISO filesystem..."
	umount -l "${ISO_RSYNC_TARGET}" >/dev/null 2>&1
	
	# Move real filesystem to proper location
	mv "${ISO_RSYNC_TARGET}.img" "${ISO_REALFS_DIR}/rootfs.img"
	
	# Create compressed squashfs overlay
	einfo "Creating compressed squashfs overlay..."
	mksquashfs "${ISO_CDROOT_DIR}" "${ISO_ROOT_DIR}/squashfs.img" \
		-b 1048576 -comp xz -Xdict-size 100%
	mv "${ISO_ROOT_DIR}/squashfs.img" "${ISO_SQUASHFS_DIR}/"
	
	einfo "========================================"
	einfo "ISO PREPARATION COMPLETE"
	einfo "========================================"
	einfo "Filesystem structure:"
	einfo "- Real filesystem: ${ISO_REALFS_DIR}/rootfs.img"
	einfo "- Compressed overlay: ${ISO_SQUASHFS_DIR}/squashfs.img"
	einfo "- Boot files: ${ISO_ROOT_DIR}/boot/"
	einfo "========================================"
}

bootloaderiso() {
	# Fetch and install GRUB2 live boot configuration
	einfo "Fetching GRUB2 boot configuration..."
	
	if git clone "https://gitlab.com/${releasename}/boot-core.git" "${BOOTLOADER_FETCH_PATH}"; then
		if [[ -d "${BOOTLOADER_CONFIGS}" ]]; then
			cp -avx "${BOOTLOADER_CONFIGS}" "${ISO_ROOT_DIR}/"
			einfo "Boot configuration installed successfully"
		else
			ewarn "Boot configuration directory not found in repository"
		fi
	else
		eerror "Failed to fetch boot configuration repository"
		exit 1
	fi
}

cleanupiso() {
	# Clean up temporary files from ISO preparation
	einfo "Cleaning up temporary files..."
	
	local cleanup_targets=(
		"${ISO_RSYNC_SOURCE}"
		"${ISO_RSYNC_TARGET}"
		"${ISO_CDROOT_DIR}"
		"${BOOTLOADER_FETCH_PATH}"
	)
	
	# Unmount any remaining mounts
	umount "${ISO_RSYNC_SOURCE}" >/dev/null 2>&1
	
	# Remove temporary directories
	for target in "${cleanup_targets[@]}"; do
		if [[ -d "${target}" ]]; then
			rm -rf "${target}"
		fi
	done
	
	einfo "Cleanup completed"
}

makeisoimg() {
	# Create final ISO image
	local iso_filename="${releasename}-${releasetarget}-${releaseversion}-${isomainarch}.iso"
	
	einfo "========================================"
	einfo "CREATING FINAL ISO IMAGE"
	einfo "========================================"
	einfo "Output file: ${iso_filename}"
	
	if grub-mkrescue \
		--mbr-force-bootable \
		-volid "ARGENT" \
		-joliet \
		-iso-level 3 \
		-o "${iso_filename}" \
		"${ISO_ROOT_DIR}"; then
		
		einfo "========================================"
		einfo "ISO CREATION SUCCESSFUL!"
		einfo "========================================"
		einfo "ISO file: ${iso_filename}"
		einfo "Size: $(du -h "${iso_filename}" | cut -f1)"
		einfo "========================================"
	else
		eerror "Failed to create ISO image"
		exit 1
	fi
}

makeiso() {
	# Main ISO creation workflow
	einfo "========================================"
	einfo "STARTING ISO CREATION PROCESS"
	einfo "========================================"
	
	checkroot
	chrootchecksum
	prepareiso "$@"
	bootloaderiso
	cleanupiso
	makeisoimg
	
	einfo "========================================"
	einfo "ISO CREATION COMPLETED SUCCESSFULLY"
	einfo "========================================"
}

# =============================================================================
# REPOSITORY MANAGEMENT FUNCTIONS
# =============================================================================

removeportagetree() {
	# Remove portage tree while preserving packages and distfiles
	if [[ -d "${PORTAGE_MAIN_DIR}/.git" ]]; then
		einfo "Removing Gentoo portage tree (preserving packages and distfiles)"
		find "${PORTAGE_MAIN_DIR}" -mindepth 1 \
			-name "packages" -prune -o \
			-name "distfiles" -prune -o \
			-exec rm -rf {} \; >/dev/null 2>&1
	fi
}

removeoverlays() {
	# Remove Argent overlay
	einfo "Removing ${releasename}-${releasetarget} overlay"
	
	if command -v layman >/dev/null 2>&1; then
		layman -d "${releasename}-${releasetarget}" >/dev/null 2>&1
		
		local layman_dir="/var/lib/layman/${releasename}-${releasetarget}"
		if [[ -d "${layman_dir}" ]]; then
			rm -rf "${layman_dir}" || die "Failed to remove layman directory"
		fi
	elif [[ -e "/var/db/repos/${releasename}-${releasetarget}" ]]; then
		if [[ -d "${ARGENT_MAIN_DIR}/.git" ]]; then
			einfo "Removing Argent overlay tree (preserving packages and distfiles)"
			find "${ARGENT_MAIN_DIR}" -mindepth 1 \
				-name "packages" -prune -o \
				-name "distfiles" -prune -o \
				-exec rm -rf {} \; >/dev/null 2>&1
		fi
	fi
}

removeportageconfig() {
	# Remove Argent build system configuration
	einfo "Removing ${releasename}-${releasetarget} build system"
	
	local config_files=(
		"${PORTAGE_LINK_CONFDIR}/make.conf"
		"${PORTAGE_LINK_CONFDIR}/make.profile"
		"${PORTAGE_LINK_CONFDIR}"
	)
	
	for config_file in "${config_files[@]}"; do
		rm -f "${config_file}" >/dev/null 2>&1
	done
	
	rm -rf "${PORTAGE_MAIN_CONFDIR}" >/dev/null 2>&1
}

resetmode() {
	# Reset system to clean state
	checkroot
	removeportagetree
	removeoverlays
	removeportageconfig
}

fetchportageconfig() {
	# Fetch Argent build system configuration
	einfo "Injecting ${releasename}-${releasetarget} build system"
	
	pushd /opt >/dev/null 2>&1 || exit 1
	git clone --branch master "${PORTAGE_REPO}"
	popd >/dev/null 2>&1 || exit 1
}

fetchfullportagetree() {
	# Fetch complete Gentoo portage tree for development/source modes
	if [[ ! -d "${PORTAGE_MAIN_DIR}/.git" ]]; then
		einfo "Injecting full Gentoo portage tree (devmode/srcmode)"
		
		# Ensure directory exists
		mkdir -p "${PORTAGE_MAIN_DIR}"
		
		cd "${PORTAGE_MAIN_DIR}" || exit 1
		git init >/dev/null 2>&1
		git remote add origin https://gitlab.com/argent/portage.git
		
		einfo "Fetching portage tree (this may take a while)..."
		git pull --depth=1 origin master
		git branch -u origin/master master
		
		# Clean up unnecessary files
		rm -rf "${PORTAGE_MAIN_DIR}/profiles/updates"
		
		einfo "Full portage tree installation completed"
	else
		einfo "Full portage tree already exists, skipping..."
	fi
}

fetchfullargentbuilddir() {
	# Fetch complete Argent build directory for development
	if [[ ! -e "${PORTAGE_MAIN_CONFDIR}/.git" ]]; then
		echo
		einfo "Injecting GIT sync to central Argent overlay..."
		einfo "This may take a moment, please stand by!"
		
		mkdir -p "${PORTAGE_MAIN_CONFDIR}"
		cd "${PORTAGE_MAIN_CONFDIR}" || exit 1
		
		git init >/dev/null 2>&1
		git remote add origin "${PORTAGE_REPO}"
		git pull --depth=1 origin master
		git branch -u origin/master master
		
		einfo "Argent build directory sync completed"
	else
		einfo "Argent build directory already exists, skipping..."
	fi
}

fetchminimalportagetree() {
	# Fetch minimal portage tree for user mode
	# Only includes profiles, metadata, and eclasses - no ebuilds
	if [[ ! -d "${PORTAGE_MAIN_DIR}" ]]; then
		mkdir -p "${PORTAGE_MAIN_DIR}"
	fi

	if [[ ! -d "${PORTAGE_MAIN_DIR}/.git" ]]; then
		einfo "Injecting minimal Gentoo portage tree (usermode)"
		einfo "This includes only profiles, metadata, and eclasses"

		cd "${PORTAGE_MAIN_DIR}" || exit 1
		git init >/dev/null 2>&1
		git remote add origin https://gitlab.com/argent/portage.git

		# Configure sparse checkout for minimal tree
		git config core.sparseCheckout true
		git config extensions.partialClone origin
		git config remote.origin.promisor true
		git config fetch.fsckObjects false
		git config remote.origin.partialCloneFilter blob:none

		# Define what to include in sparse checkout
		local sparse_paths=(
			"profiles/"
			"metadata/"
			"eclass/"
			".gitignore"
		)

		{
			for path in "${sparse_paths[@]}"; do
				echo "${path}"
			done
		} > .git/info/sparse-checkout

		# Fetch and configure
		git fetch --depth=1 origin master
		git checkout master
		git branch -u origin/master master

		git sparse-checkout init --cone
		git sparse-checkout set profiles metadata eclass .gitignore

		# Cleanup to save space
		git reflog expire --expire=now --all
		git gc --prune=now --aggressive

		# Remove unnecessary profile updates and architectures
		rm -rf profiles/updates
		find profiles/default/linux/ -mindepth 1 -maxdepth 1 -type d ! -name amd64 -exec rm -rf {} + 2>/dev/null

		einfo "Minimal portage tree installation completed"
	else
		einfo "Minimal portage tree already exists, skipping..."
	fi
}

fetchminimalargenttree() {
	# Fetch minimal Argent overlay tree for user mode
	# Only includes profiles, metadata, and eclasses
	if [[ ! -d "${ARGENT_MAIN_DIR}" ]]; then
		mkdir -p "${ARGENT_MAIN_DIR}"
	fi

	if [[ ! -d "${ARGENT_MAIN_DIR}/.git" ]]; then
		einfo "Injecting minimal Argent overlay tree (usermode)"

		cd "${ARGENT_MAIN_DIR}" || exit 1
		git init >/dev/null 2>&1
		git remote add origin https://gitlab.com/argent/argent-ws.git

		# Configure sparse checkout for minimal tree
		git config core.sparseCheckout true
		git config extensions.partialClone origin
		git config remote.origin.promisor true
		git config fetch.fsckObjects false
		git config remote.origin.partialCloneFilter blob:none

		# Define sparse checkout paths
		local sparse_paths=(
			"profiles/"
			"metadata/"
			"eclass/"
			".gitignore"
		)

		{
			for path in "${sparse_paths[@]}"; do
				echo "${path}"
			done
		} > .git/info/sparse-checkout

		# Fetch and configure repository
		git fetch --depth=1 origin master
		git checkout master
		git branch -u origin/master master

		git sparse-checkout init --cone
		git sparse-checkout set profiles metadata eclass .gitignore

		# Initialize and update submodules with minimal depth
		git submodule update --init --recursive --depth=1

		# Cleanup to minimize disk usage
		git reflog expire --expire=now --all
		git gc --prune=now --aggressive

		# Cleanup submodules as well
		git submodule foreach --recursive \
			'git reflog expire --expire=now --all && git gc --prune=now --aggressive'

		# Remove unnecessary files
		rm -rf profiles/updates

		einfo "Minimal Argent overlay tree installation completed"
	else
		einfo "Minimal Argent overlay tree already exists, skipping..."
	fi
}

fetchoverlays() {
	# Fetch Argent overlay using appropriate method
	einfo "Injecting ${releasename}-${releasetarget} overlay"

	if command -v layman >/dev/null 2>&1; then
		# Use layman if available
		local overlay_url="https://gitlab.com/${releasename}/${releasename}-${releasetarget}/raw/master/overlay.xml"
		echo y | layman -f -a "${releasename}-${releasetarget}" -o "${overlay_url}"
	else
		# Use emerge --sync as fallback
		emerge --sync "${releasename}-${releasetarget}"
	fi
}

# ============================================================================
# System Mode Configuration Functions
# ============================================================================

setbinmodeconfig() {
	# Configure system for binary-only mode (usermode)
	# Uses precompiled packages from binhost exclusively
	einfo "Configuring binary mode (usermode)"
	
	ln -sf "${PORTAGE_GITDIR}" "${PORTAGE_LINK_CONFDIR}"
	ln -sf "${PORTAGE_LINK_CONFDIR}/make.conf.amd64-user" "${PORTAGE_LINK_CONFDIR}/make.conf"
	
	# Set appropriate Gentoo profile
	eselect profile set "default/linux/amd64/23.0/desktop/plasma/systemd"
	
	# Update environment
	env-update
	source /etc/profile
	
	einfo "Binary mode configuration completed"
}

setmixedmodeconfig() {
	# Configure system for mixed mode (development)
	# Prefers binary packages but falls back to source when needed
	einfo "Configuring mixed mode (development)"
	
	ln -sf "${PORTAGE_GITDIR}" "${PORTAGE_LINK_CONFDIR}"
	ln -sf "${PORTAGE_LINK_CONFDIR}/make.conf.amd64-devel" "${PORTAGE_LINK_CONFDIR}/make.conf"
	
	# Set appropriate Gentoo profile  
	eselect profile set "default/linux/amd64/23.0/desktop/plasma/systemd"
	
	# Update environment
	env-update
	source /etc/profile
	
	einfo "Mixed mode configuration completed"
}

setsrcmodeconfig() {
	# Configure system for source-only mode
	# Uses source ebuilds exclusively, ignores binary packages
	einfo "Configuring source mode"
	
	ln -sf "${PORTAGE_GITDIR}" "${PORTAGE_LINK_CONFDIR}"
	ln -sf "${PORTAGE_LINK_CONFDIR}/make.conf.amd64-srcmode" "${PORTAGE_LINK_CONFDIR}/make.conf"
	
	# Set appropriate Gentoo profile
	eselect profile set "default/linux/amd64/23.0/desktop/plasma/systemd"
	
	# Update environment
	env-update
	source /etc/profile
	
	einfo "Source mode configuration completed"
}

setsrcmodecustom() {
	# Configure system for custom source mode
	# Full control over USE flags and compilation options
	einfo "Configuring custom source mode"
	
	ln -sf "${PORTAGE_GITDIR}" "${PORTAGE_LINK_CONFDIR}"
	ln -sf "${PORTAGE_LINK_CONFDIR}/make.conf.amd64-custom" "${PORTAGE_LINK_CONFDIR}/make.conf"
	
	# Set appropriate Gentoo profile
	eselect profile set "default/linux/amd64/23.0/desktop/plasma/systemd"
	
	# Update environment
	env-update
	source /etc/profile
	
	einfo "Custom source mode configuration completed"
}

# ============================================================================
# Primary System Mode Functions
# ============================================================================

check_portage_directory() {
	local current_dir
	current_dir=$(pwd)
	
	if [[ "${current_dir}" == "/etc/portage"* ]]; then
		ewarn "You are currently in the /etc/portage directory"
		ewarn "This directory will be modified during mode switching"
		einfo "Changing to /etc/ directory for safety..."
		cd /etc/ || {
			eerror "Failed to change to /etc/ directory"
			exit 1
		}
		einfo "Directory changed to: $(pwd)"
	fi
}

binmode() {
	# Initialize binary-only mode (usermode)
	einfo "Setting up binary mode (usermode)"
	
	check_portage_directory
	resetmode
	fetchportageconfig
	fetchminimalportagetree
	fetchminimalargenttree
	setbinmodeconfig
	
	einfo "Binary mode setup completed"
}

mixedmode() {
	# Initialize mixed development mode
	einfo "Setting up mixed mode (development)"
	
	check_portage_directory
	resetmode
	fetchportageconfig
	fetchfullportagetree
	setmixedmodeconfig
	fetchoverlays
	
	einfo "Mixed mode setup completed"
}

srcmode() {
	# Initialize source-only mode
	einfo "Setting up source mode"
	
	check_portage_directory
	resetmode
	fetchportageconfig
	fetchfullportagetree
	setsrcmodeconfig
	fetchoverlays
	
	einfo "Source mode setup completed"
}

srccustom() {
	# Initialize custom source mode with user-defined configuration
	einfo "Setting up custom source mode"
	
	check_portage_directory
	resetmode
	fetchportageconfig
	fetchfullportagetree
	fetchoverlays
	
	echo
	if [[ -e "${PORTAGE_MAIN_CONFDIR}" ]]; then
		# Create custom configuration if it doesn't exist
		if [[ ! -e "${PORTAGE_LINK_CONFDIR}/make.conf.amd64-custom" ]]; then
			cp "${PORTAGE_LINK_CONFDIR}/make.conf.amd64-devel" "${PORTAGE_LINK_CONFDIR}/make.conf.amd64-custom"
		fi
		
		# Clean up git history for custom configuration
		rm -rf "${PORTAGE_MAIN_CONFDIR}/.git"
		
		# Remove default package configuration
		rm -rf "${PORTAGE_MAIN_CONFDIR}/conf/intel/portage/package.keywords/"*
		rm -rf "${PORTAGE_MAIN_CONFDIR}/conf/intel/portage/package.use/"*
	fi
	echo
	
	setsrcmodecustom
	einfo "Custom source mode setup completed"
}


# ============================================================================
# Decentralized Mode Functions
# ============================================================================

decentralized_user() {
	# Configure decentralized user mode - independent precompiled system
	einfo "Configuring decentralized user mode"
	
	if [[ -e "${PORTAGE_MAIN_CONFDIR}" ]]; then
		# Configure for binary packages
		rm -f "${PORTAGE_LINK_CONFDIR}/make.conf"
		ln -sf "${PORTAGE_LINK_CONFDIR}/make.conf.amd64-user" "${PORTAGE_LINK_CONFDIR}/make.conf"
		ln -sf "${PORTAGE_LINK_CONFDIR}/binhost-main.conf" "${PORTAGE_LINK_CONFDIR}/binhost.conf"
		
		# Set Gentoo profile
		eselect profile set "default/linux/amd64/23.0/desktop/plasma/systemd"
		
		# Update environment
		env-update
		source /etc/profile
		
		einfo "Decentralized user mode configured"
	else
		ewarn "Clone directory not found: ${PORTAGE_MAIN_CONFDIR}"
	fi
}

decentralized_devel() {
	# Configure decentralized development mode
	einfo "Configuring decentralized development mode"
	
	if [[ -e "${PORTAGE_MAIN_CONFDIR}" ]]; then
		# Configure for mixed binary/source usage
		ln -sf "${PORTAGE_LINK_CONFDIR}/make.conf.amd64-devel" "${PORTAGE_LINK_CONFDIR}/make.conf"
		ln -sf "${PORTAGE_LINK_CONFDIR}/binhost-main.conf" "${PORTAGE_LINK_CONFDIR}/binhost.conf"
		
		# Set Gentoo profile
		eselect profile set "default/linux/amd64/23.0/desktop/plasma/systemd"
		
		# Update environment
		env-update
		source /etc/profile
		
		einfo "Decentralized development mode configured"
	else
		ewarn "Clone directory not found: ${PORTAGE_MAIN_CONFDIR}"
	fi
}

decentralized_source() {
	# Configure decentralized source-only mode
	einfo "Configuring decentralized source mode"
	
	if [[ -e "${PORTAGE_MAIN_CONFDIR}" ]]; then
		# Configure for source-only compilation
		ln -sf "${PORTAGE_LINK_CONFDIR}/make.conf.amd64-srcmode" "${PORTAGE_LINK_CONFDIR}/make.conf"
		ln -sf "${PORTAGE_LINK_CONFDIR}/binhost-main.conf" "${PORTAGE_LINK_CONFDIR}/binhost.conf"
		
		# Set Gentoo profile
		eselect profile set "default/linux/amd64/23.0/desktop/plasma/systemd"
		
		# Update environment
		env-update
		source /etc/profile
		
		einfo "Decentralized source mode configured"
	else
		ewarn "Clone directory not found: ${PORTAGE_MAIN_CONFDIR}"
	fi
}

decentralized_custom() {
	# Configure decentralized custom mode
	einfo "Configuring decentralized custom mode"
	
	if [[ -e "${PORTAGE_MAIN_CONFDIR}" ]]; then
		# Create custom configuration if needed
		if [[ ! -e "${PORTAGE_LINK_CONFDIR}/make.conf.amd64-custom" ]]; then
			cp "${PORTAGE_LINK_CONFDIR}/make.conf.amd64-devel" "${PORTAGE_LINK_CONFDIR}/make.conf.amd64-custom"
		fi
		
		# Configure for custom usage
		ln -sf "${PORTAGE_LINK_CONFDIR}/make.conf.amd64-custom" "${PORTAGE_LINK_CONFDIR}/make.conf"
		ln -sf "${PORTAGE_LINK_CONFDIR}/binhost-main.conf" "${PORTAGE_LINK_CONFDIR}/binhost.conf"
		
		# Set Gentoo profile
		eselect profile set "default/linux/amd64/23.0/desktop/plasma/systemd"
		
		# Update environment
		env-update
		source /etc/profile
		
		einfo "Decentralized custom mode configured"
	else
		ewarn "Clone directory not found: ${PORTAGE_MAIN_CONFDIR}"
	fi
}

decentralized_gentoo() {
	# Configure pure Gentoo mode - complete independence from Argent
	ewarn "Configuring pure Gentoo mode (one-way operation!)"
	
	if [[ -e "${PORTAGE_MAIN_CONFDIR}" ]]; then
		# Create custom configuration if needed
		if [[ ! -e "${PORTAGE_LINK_CONFDIR}/make.conf.amd64-custom" ]]; then
			cp "${PORTAGE_LINK_CONFDIR}/make.conf.amd64-devel" "${PORTAGE_LINK_CONFDIR}/make.conf.amd64-custom"
		fi
		
		# Configure for pure Gentoo
		ln -sf "${PORTAGE_LINK_CONFDIR}/make.conf.amd64-custom" "${PORTAGE_LINK_CONFDIR}/make.conf"
		ln -sf "${PORTAGE_LINK_CONFDIR}/binhost-main.conf" "${PORTAGE_LINK_CONFDIR}/binhost.conf"
		
		# Set Gentoo profile
		eselect profile set "default/linux/amd64/23.0/desktop/plasma/systemd"
		
		# Update environment
		env-update
		source /etc/profile
	fi
	
	# Remove Argent-specific git configuration
	rm -rf "${PORTAGE_LINK_CONFDIR}/.git"
	
	# Clean up Argent-specific package configurations
	local gitignore_keywords="${PORTAGE_MAIN_CONFDIR}/conf/intel/portage/package.keywords/.gitignore"
	local gitignore_use="${PORTAGE_MAIN_CONFDIR}/conf/intel/portage/package.use/.gitignore"
	
	if [[ -f "${gitignore_keywords}" ]]; then
		sed -i 's|!||g' "${gitignore_keywords}"
		while IFS= read -r keyword_file; do
			if [[ "${keyword_file}" == *"keyword"* ]]; then
				rm -f "${PORTAGE_MAIN_CONFDIR}/conf/intel/portage/package.keywords/${keyword_file}"
			fi
		done < "${gitignore_keywords}"
	fi
	
	if [[ -f "${gitignore_use}" ]]; then
		sed -i 's|!||g' "${gitignore_use}"
		while IFS= read -r use_file; do
			if [[ "${use_file}" == *"use"* ]]; then
				rm -f "${PORTAGE_MAIN_CONFDIR}/conf/intel/portage/package.use/${use_file}"
			fi
		done < "${gitignore_use}"
	fi
	
	einfo "Pure Gentoo mode configured"
	einfo "System is now completely independent from Argent"
}
# =============================================================================
# HELP SYSTEM
# =============================================================================

showhelp() {
	# Color definitions for help output
	local COLOR_HEADER="\e[1;34m"
	local COLOR_RESET="\e[0m"
	local COLOR_WARN="\e[1;33m"
	
	echo -e "${COLOR_HEADER}SYNOPSIS${COLOR_RESET}"
	echo -e "	${COLOR_HEADER}avasile --option${COLOR_RESET} [${COLOR_HEADER}arguments${COLOR_RESET}]"
	echo -e "	${COLOR_HEADER}avasile --help${COLOR_RESET}"
	echo
	echo -e "${COLOR_HEADER}DESCRIPTION${COLOR_RESET}"
	echo -e "	Vasile is an acronym for \"Versatile Advanced Script for ISOs and Latest Enhancements\""
	echo -e "	Avasile stands for \"Argent Vasile\""
	echo
	echo -e "${COLOR_HEADER}OPTIONS${COLOR_RESET}"
	echo -e "	${COLOR_HEADER}--status${COLOR_RESET}"
	echo -e "		Show the current Avasile mode (user, devel, source, custom, non-custom)"
	echo
	echo -e "	${COLOR_HEADER}--makepkg${COLOR_RESET} [${COLOR_HEADER}package(s)${COLOR_RESET}]"
	echo -e "		Build package(s) in an overlayfs-mounted squashfs chroot environment."
	echo -e "		"
	echo -e "		Must be run in the directory containing the squashfs chroot, or it will fail."
	echo -e "		The squashfs chroot and MD5 checksum file paths are defined in ${COLOR_HEADER}libavasile${COLOR_RESET}."
	echo -e "		"
	echo -e "		You MUST provide package(s) to build, or avasile will only mount the chroot."
	echo -e "		"
	echo -e "		Examples:"
	echo -e "			${COLOR_HEADER}avasile --makepkg wine${COLOR_RESET}"
	echo -e "			${COLOR_HEADER}avasile --makepkg wine playonlinux q4wine${COLOR_RESET}"
	echo -e "		"
	echo -e "		If packages are already built, they will be installed (unless newer versions are available)."
	echo -e "		Dependencies will use existing built packages when available."
	echo
	echo -e "	${COLOR_HEADER}--makeiso${COLOR_RESET} [${COLOR_HEADER}package_list_file(s)${COLOR_RESET}]"
	echo -e "		Build a live ISO image based on the squashfs chroot."
	echo -e "		"
	echo -e "		Must be run in the directory containing the squashfs chroot."
	echo -e "		"
	echo -e "		The process will:"
	echo -e "		- Rsync chroot contents to ISO filesystem"
	echo -e "		- Allow package installation (interactive or from provided lists)"
	echo -e "		- Compress live filesystem"
	echo -e "		- Auto-enable live services"
	echo -e "		- Configure live bootloader"
	echo -e "		- Generate final ISO image"
	echo -e "		"
	echo -e "		Package sets are available in ${COLOR_HEADER}/etc/portage/sets${COLOR_RESET}."
	echo -e "		"
	echo -e "		Examples:"
	echo -e "			${COLOR_HEADER}avasile --makeiso${COLOR_RESET} (interactive mode)"
	echo -e "			${COLOR_HEADER}avasile --makeiso /etc/portage/sets/artwork${COLOR_RESET} (automated)"
	echo
	echo -e "	${COLOR_HEADER}--resetmode${COLOR_RESET}"
	echo -e "		Reset system state by removing portage tree, overlays, and configuration."
	echo -e "		"
	echo -e "		${COLOR_WARN}WARNING:${COLOR_RESET} Never leave the system in this state! You will be unable to"
	echo -e "		install/remove/upgrade packages until you configure portage manually or"
	echo -e "		activate one of the supported system states."
	echo
	echo -e "	${COLOR_HEADER}--usermode${COLOR_RESET}"
	echo -e "		Switch to binary-only mode (usermode)."
	echo -e "		"
	echo -e "		- Uses only binary packages from binhost"
	echo -e "		- Fetches minimal portage tree (profiles, metadata, eclass only)"
	echo -e "		- Configures ${COLOR_HEADER}make.conf${COLOR_RESET} for binary usage"
	echo -e "		- Suitable for Gentoo newcomers"
	echo -e "		"
	echo -e "		${COLOR_WARN}WARNING:${COLOR_RESET} Do not modify files in ${COLOR_HEADER}/etc/portage/${COLOR_RESET} in this mode."
	echo
	echo -e "	${COLOR_HEADER}--devmode${COLOR_RESET}"
	echo -e "		Switch to mixed mode (development mode)."
	echo -e "		"
	echo -e "		- Prefers binary packages over ebuilds"
	echo -e "		- Falls back to ebuilds when needed"
	echo -e "		- Fetches full portage tree and overlays"
	echo -e "		- Allows custom USE flags and keywords"
	echo -e "		"
	echo -e "		Create files like ${COLOR_HEADER}100-my.package.use${COLOR_RESET} in ${COLOR_HEADER}/etc/portage/package.use/${COLOR_RESET}"
	echo -e "		for custom configurations."
	echo
	echo -e "	${COLOR_HEADER}--srcmode${COLOR_RESET}"
	echo -e "		Switch to source-only mode."
	echo -e "		"
	echo -e "		- Transforms system to pure Gentoo (source-based)"
	echo -e "		- Ignores binary packages"
	echo -e "		- Uses ebuilds exclusively"
	echo -e "		- Still synced with main Argent overlay"
	echo -e "		"
	echo -e "		${COLOR_WARN}WARNING:${COLOR_RESET} Requires strong knowledge of Gentoo tools:"
	echo -e "		${COLOR_HEADER}emerge, equery, layman, eix, qlist, useflags, keywords, masks${COLOR_RESET}"
	echo
	echo -e "	${COLOR_HEADER}--custom${COLOR_RESET}"
	echo -e "		Switch to custom source mode."
	echo -e "		"
	echo -e "		- Full Gentoo system with optional binary packages"
	echo -e "		- Modify all USE flags freely"
	echo -e "		- Packages recompiled when USE flags change"
	echo -e "		- Complete control over system configuration"
	echo

	echo
	echo -e "	${COLOR_HEADER}--decentralize-user${COLOR_RESET}"
	echo -e "		Decentralized user mode - independent precompiled system."
	echo -e "		"
	echo -e "		Requires advanced Gentoo knowledge with binhost configuration."
	echo -e "		Run 'epkg update' or 'emerge --sync' after mode switches."
	echo
	echo -e "	${COLOR_HEADER}--decentralize-dev${COLOR_RESET}"
	echo -e "		Decentralized development mode - independent development system."
	echo -e "		"
	echo -e "		Modify USE flags and /etc/portage freely while prioritizing binhost packages."
	echo -e "		Run 'epkg update' or 'emerge --sync' after mode switches."
	echo
	echo -e "	${COLOR_HEADER}--decentralize-source${COLOR_RESET}"
	echo -e "		Decentralized source-only mode - independent source system."
	echo -e "		"
	echo -e "		No longer prioritizes Argent binaries, uses source ebuilds exclusively."
	echo -e "		Requires expert Gentoo knowledge."
	echo -e "		Run 'epkg update' or 'emerge --sync' after mode switches."
	echo
	echo -e "	${COLOR_HEADER}--decentralize-custom${COLOR_RESET}"
	echo -e "		Decentralized custom mode - independent custom system."
	echo -e "		"
	echo -e "		Like --custom but decentralized from Argent repositories."
	echo -e "		Run 'epkg update' or 'emerge --sync' after mode switches."
	echo
	echo -e "	${COLOR_HEADER}--decentralize-gentoo${COLOR_RESET}"
	echo -e "		Pure Gentoo mode - complete independence from Argent."
	echo -e "		"
	echo -e "		${COLOR_WARN}WARNING:${COLOR_RESET} One-way ticket! System forgets it was ever Argent."
	echo -e "		Total user control but no central authority."
	echo -e "		"
	echo -e "		To return to centralized Argent:"
	echo -e "			cd /etc/portage && git init"
	echo -e "			git remote add origin ${PORTAGE_REPO}"
	echo -e "			git pull --depth=1 origin master"
	echo -e "			git branch -u origin/master master"
	echo
	exit 0
}
