#!/bin/bash
set -xeu

CYAN="\033[0;36m"
NORMAL="\033[0m"

# CHANGE THESE
ROOT_PART="/dev/sda2"
EFI_PART="/dev/sda1"
HOME_PART="/dev/sdb1"

TARGET_HOSTNAME="artixBTW"
USERNAME="User"

DISKFORMATTYPE="ext4"
DISKLABELTYPE="gpt"

PACMAN_PKGS="
	base base-devel
	openrc elogind-openrc dbus-openrc
	linux linux-firmware
	sudo vim git jj curl
	grub efibootmgr
	networkmanager-openrc
	i2pd neofetch
	xinit xsetroot xrandr xinput
	libx11 libxft libxinerama
	hsetroot dmenu
	awesome
	ghostty
"

NIX_PKGS="
	nixpkgs.fastcompmgr
	nixpkgs.ghostty
"

PKGIT="fastcompmgr"

title() {
    clear
    echo -ne "${CYAN}
################################################################################
#                                                                              #
#  						Welcome to Artix						    #
#                                                                              #
#                                    By								    #
#                                        							    #
#                                 1negroup                                     #
#                               			                                  #
#                    Modified Script Made By Hein Oke Soe                      #
################################################################################
${NORMAL}
"
}

check_password()
{
	if [ "$2" = "$3" ]
	then
		export "$1=$2"
		return 0
	else
		printf "%s\n" "ERROR: Passwords do not match. Try again."
		return 1
	fi
}

show_disks()
{
	echo
	echo "Current disks and partitions:"
	echo

	lsblk -o NAME,SIZE,FSTYPE,LABEL,UUID,MOUNTPOINTS

	echo
}

start_install()
{

	show_disks
	read -rp "Look at the disk list above, then press Enter to continue..."

	while true
	do
		read -srp "Enter root password: " password
		echo
		read -srp "Enter root password again: " password_1
		echo

		check_password ROOT_PASSWORD "$password" "$password_1"

		if [ "$?" -eq 0 ]
		then
			break
		fi
	done

	read -rp "Enter username [User]: " USERNAME
	USERNAME="${USERNAME:-theatlas}"
	export USERNAME

	while true
	do
		read -srp "Enter password for $USERNAME: " password
		echo
		read -srp "Enter password for $USERNAME again: " password_1
		echo

		check_password USER_PASSWORD "$password" "$password_1"

		if [ "$?" -eq 0 ]
		then
			break
		fi
	done

	read -rp "Enter hostname [${TARGET_HOSTNAME}]: " TARGET_HOSTNAME
	TARGET_HOSTNAME="${TARGET_HOSTNAME:-artixBTW}"
	export TARGET_HOSTNAME

	show_disks
	read -rp "Look at the disk list above, then press Enter to continue..."

	read -rp "Enter disk format type [${DISKFORMATTYPE}]: " input_format
	DISKFORMATTYPE="${input_format:-$DISKFORMATTYPE}"
	export DISKFORMATTYPE

	read -rp "Enter root partition [$ROOT_PART]: " input_root
	ROOT_PART="${input_root:-$ROOT_PART}"
	export ROOT_PART

	read -rp "Enter EFI partition [$EFI_PART]: " input_efi
	EFI_PART="${input_efi:-$EFI_PART}"
	export EFI_PART

	read -rp "Enter external home partition [$HOME_PART]: " input_home
	HOME_PART="${input_home:-$HOME_PART}"
	export HOME_PART
}

part_name()
{
	case "$1" in
		*nvme*|*mmcblk*)
			printf "%sp%s" "$1" "$2"
			;;
		*)
			printf "%s%s" "$1" "$2"
			;;
	esac
}

choose_disk()
{
	echo -e "\nSelect the disk to install: "

	mapfile -t options < <(
		lsblk -dn --output NAME,SIZE,MODEL |
		awk '{print "/dev/"$1"("$2" "$3" "$4" "$5")"}'
	)

	select_option 0 1 "${options[@]}"
	choice=$?

	export chosen_disk="${options[$choice]}"
	export target_device="${chosen_disk%%(*}"
}

part_disk()
{
	log "${1:-Creating partitions}"

	is_uefi="yes"

	if [[ ! -d /sys/firmware/efi ]]
	then
		is_uefi="no"
	fi

	export is_uefi

	swapoff -a || true
	umount -R "$target_mount_point" 2>/dev/null || true

	for part in $(lsblk -lnpo NAME "$target_device" | tail -n +2)
	do
		umount "$part" 2>/dev/null || true
		swapoff "$part" 2>/dev/null || true
		wipefs -a "$part" || true
	done

	wipefs -a "$target_device" || true
	sfdisk --delete "$target_device" || true

	if [[ "$is_uefi" == "yes" ]]
	then
		sfdisk -q --force --label gpt "$target_device" <<EOF
,${boot_partition_size},U,*
,${swap_partition_size},S
,${root_partition_size},L
,${home_partition_size},L
EOF
	else
		sfdisk -q --force --label dos "$target_device" <<EOF
,${boot_partition_size},0c,*
,${swap_partition_size},S
,${root_partition_size},L
,${home_partition_size},L
EOF
	fi

	partprobe "$target_device" || true
	udevadm settle || true
	sleep 2
}

format_disk()
{
	log "${1:-Formatting partitions}"

	boot_partition="$(part_name "$target_device" 1)"
	swap_partition="$(part_name "$target_device" 2)"
	root_partition="$(part_name "$target_device" 3)"
	home_partition="$(part_name "$target_device" 4)"

	export boot_partition
	export swap_partition
	export root_partition
	export home_partition

	mkfs.fat -F32 "$boot_partition"

	if [[ "$is_uefi" == "yes" ]]
	then
		fatlabel "$boot_partition" EFI
	else
		fatlabel "$boot_partition" BOOT
	fi

	mkswap -L SWAP "$swap_partition"

	if [[ "$filesystem" == "$DISKFORMATTYPE" ]]
	then
		mkfs.btrfs -f -L ARTIX "$root_partition"
	else
		mkfs.ext4 -F -L ARTIX "$root_partition"
	fi

	# I would keep /home ext4 even if root is btrfs.
	mkfs.ext4 -F -L HOME "$home_partition"
}

mount_disk()
{
	log "${1:-Mounting partitions}"

	mount "$root_partition" "$target_mount_point"

	if [[ "$filesystem" == "$DISKFORMATTYPE" ]]
	then
		btrfs subvolume create "$target_mount_point/@"

		umount "$target_mount_point"
		mount -o subvol=@ "$root_partition" "$target_mount_point"
	fi

	mkdir -p "$target_mount_point/boot/efi"
	mount "$boot_partition" "$target_mount_point/boot/efi"

	swapon "$swap_partition"

	mkdir -p "$target_mount_point/home"
	mount "$home_partition" "$target_mount_point/home"
}

setup_disk()
{
	run_step "Creating partitions       " part_disk
	run_step "Formatting partitions     " format_disk
	run_step "Mounting partitions       " mount_disk
}

confirm()
{
	echo
	echo "WARNING: Artix Linux will be installed on:"
	echo
	echo "  Disk: $target_device"
	echo
	echo "This will create:"
	echo
	echo "  p1 boot/EFI  size: $boot_partition_size"
	echo "  p2 swap      size: $swap_partition_size"
	echo "  p3 root      size: $root_partition_size"
	echo "  p4 home      size: ${home_partition_size:-remaining space}"
	echo
	echo "THIS WILL ERASE THE DISK."
	echo

	options=("Yes" "No")
	select_option 0 1 "${options[@]}"

	case $? in
		0)
			setup_disk
			;;
		1)
			exit 1
			;;
	esac
}

mount_base()
{
	mount "$ROOT_PART" /mnt

	mkdir -p /mnt/boot/efi
	mount "$EFI_PART" /mnt/boot/efi

	# External hard drive as /home
	mkdir -p /mnt/home
	mount "$HOME_PART" /mnt/home
}

install_base()
{
	basestrap /mnt $PACMAN_PKGS

	# Since /mnt/home is already mounted, this should add /home to fstab.
	fstabgen -U /mnt >> /mnt/etc/fstab

	cp "$0" /mnt/root/install.sh
	chmod +x /mnt/root/install.sh
}

chroot_part()
{
	artix-chroot /mnt /root/install.sh chroot
}

inside_chroot()
{
	ln -sf /usr/share/zoneinfo/America/Chicago /etc/localtime
	hwclock --systohc

	sed -i 's/^#en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/' /etc/locale.gen
	locale-gen
	echo 'LANG=en_US.UTF-8' > /etc/locale.conf

	echo "$TARGET_HOSTNAME" > /etc/hostname
	echo "hostname=\"$TARGET_HOSTNAME\"" > /etc/conf.d/hostname

	cat > /etc/hosts <<EOF
127.0.0.1	localhost
::1		localhost
127.0.1.1	$TARGET_HOSTNAME.localdomain $TARGET_HOSTNAME
EOF

	rc-update add dbus default
	rc-update add elogind default
	rc-update add NetworkManager default

	if [ -x /etc/init.d/i2pd ]
	then
		rc-update add i2pd default
	fi

	passwd

	useradd -m -G wheel "$USERNAME"
	passwd "$USERNAME"

	echo "%wheel ALL=(ALL:ALL) ALL" > /etc/sudoers.d/wheel
	chmod 0440 /etc/sudoers.d/wheel

	grub-install --target=x86_64-efi --efi-directory=/boot/efi --bootloader-id=Artix
	grub-mkconfig -o /boot/grub/grub.cfg

	cat > "/home/$USERNAME/.xinitrc" <<'EOF'
export PATH="$HOME/.nix-profile/bin:/nix/var/nix/profiles/default/bin:$PATH"

fastcompmgr -o 0.4 -r 12 -c -C &
hsetroot -cover "$HOME/Pictures/wallpaper.png" &
exec awesome
EOF

	chown "$USERNAME:$USERNAME" "/home/$USERNAME/.xinitrc"
}

case "${1:-live}" in
	live)
		title
		start_install
		mount_base
		install_base
		chroot_part
		;;
	chroot)
		inside_chroot
		;;
esac