#!/bin/bash

# Exit on error and pipeline failure
set -eo pipefail

# ---MAIN SCRIPT---
main() {
	clear
	# cli arguments
	if [[ "$#" -ne 1 && "$#" -ne 6 || "$#" -eq 6 && "$2" != "--unattended" ]]; then
		echo "Syntax: bash $0 </dev/sdX> [--unattended <hostname> <username> <pwhash> <swapsize>]"
		echo "Note: for unattended installation, swapsize 0 = memsize. Also, LUKS is not available for security reasons and profile is assumed to be cli."
		exit 1
	fi

	export disk="$1"

	if [[ -d /sys/firmware/efi ]]; then
		export efi=1
	else
		export efi=0
	fi

	if [[ "$2" == "--unattended" ]]; then
		export unattended="true"
		export keylayout="us"
		export profile="cli"
		export luks="false"
		export hostname="$3"
		export user="$4"
		export password="$5"
		swapsize=$(cat /proc/meminfo | grep MemTotal | awk '{ print $2 }')
		swapsize=$(($swapsize/1000))"M"
		if [[ "$6" != "0" ]]; then
			swapsize="$6"
		fi
		export swapsize
		if test -n "$(find /etc/systemd/network -name '??-cloud-init*.network' -print -quit)"; then
			export cinetwork="/etc/systemd/network"
		fi
		if grep -q "console=ttyS0" /proc/cmdline; then
			export consoleboot="console=ttyS0"
			if [[ $(tty) != "/dev/ttyS0" ]]; then
				exit 1
			fi
		fi
		install
	fi

	# Keyboard layout selection
	export keylayout="us"
	loadkeys us
	confirm "Do you want to change the keymap from 'us' to 'de-latin1'? [y/N]" && export keylayout="de-latin1" && loadkeys de-latin1
	echo "Keymap set to $keylayout."
	clear

	# profile selection
	echo "Profiles:"
	echo "cli:        barebones system, no Xorg, no DE, no WM. Primarily for servers."
	echo "i3:         tiling window manager"
	echo "kde:        KDE desktop environment + big software selection"
	echo "gnome:      GNOME desktop environment + software selection"
	echo
	read -p "Profile Selection > " profile

	if [[ "$profile" != "cli" && "$profile" != "i3" && "$profile" != "kde" && "$profile" != "gnome" ]]; then
		echo "Invalid profile."
		exit 1
	fi

	# LUKS selection
	clear
	if [[ "$efi" -eq 0 ]]; then
		echo "archx does not support LUKS on legacy BIOS systems, skipping..."
		export luks="false"
	else
		echo "Encryption:"
		export luks="false"
		confirm "Do you want to encrypt your system and swap partitions? [y/N]" && export luks="true"
	fi

	# Swap size selection
	clear
	swapsize=$(cat /proc/meminfo | grep MemTotal | awk '{ print $2 }')
	swapsize=$(($swapsize/1000))"M"
	echo "Swap size: $swapsize"
	confirm "Per default swap is sized equal to RAM. Customize? [y/N]" && read -p "New swap size > " swapsize
	export swapsize

	# Hostname selection
	clear
	read -p "Hostname > " hostname
	export hostname

	# User/Pass
	clear
	echo "NOTICE: Keyboard layout is $keylayout!"

	if [ "$luks" == "true" ]; then
		while [[ "$lukspass" != "$lukspass_verify" ]] || [[ "$lukspass" == "" ]]; do
			read -s -p "LUKS password > " lukspass
			echo
			read -s -p "LUKS password (confirm) > " lukspass_verify
			echo
		done
		export lukspass
	fi

	read -p "Username > " user
	export user

	while [[ "$password" != "$password_verify" ]] || [[ "$password" == "" ]]; do
		read -s -p "User password > " password
		echo
		read -s -p "User password (confirm) > " password_verify
		echo
	done
	export password

	# VM specific stuff
	if test -n "$(find /etc/systemd/network -name '??-cloud-init*.network' -print -quit)"; then
		export cinetwork="/etc/systemd/network"
	fi

	if grep -q "console=ttyS0" /proc/cmdline; then
		export consoleboot="console=ttyS0"
	fi

	# Summary
	clear
	echo "---Summary---"
	echo "Target disk: $disk"
	if [[ $efi -eq 1 ]]; then
		echo "Mode: UEFI"
	else
		echo "Mode: Legacy/CSM/BIOS"
	fi
	if [[ -n $cinetwork ]]; then
		echo "Network: cloud-init"
	fi
	if [[ -n $consoleboot ]]; then
		echo "Console boot: enabled"
	fi
	echo "LUKS: $luks"
	echo "Swap size: $swapsize"
	echo
	echo "Profile: $profile"
	echo
	echo "Keymap: $keylayout"
	echo "Hostname: $hostname"
	echo "Username: $user"
	echo

	confirm "Everything correct? [FINAL PROMPT] [y/N]" && install
	echo "Canceling setup."
}

# ---INSTALLER FUNCTIONS---
# Main install function
install(){
	clear
	echo "---ArchLinux install start---"
	pacman_setup
	partition_disk
	format_root
	mkdir /mnt/{boot,home} 2>/dev/null
	if [[ $efi -eq 1 ]]; then
		mount $bootdev /mnt/boot
	fi
	pacstrap /mnt base base-devel wget btrfs-progs cryptsetup device-mapper dhcpcd e2fsprogs inetutils linux-firmware linux logrotate lvm2 man-db man-pages mdadm nano netctl perl sysfsutils texinfo usbutils vim xfsprogs openssh pacutils # start the actual install
	swapsetup
	basic_postinstall
	setup_initramfs
	install_bootloader
	profile_postinstall
	unmount
	if [[ "$unattended" == "true" ]]; then
		reboot
	fi
	echo "Installation complete! Please reboot now."
	exit 0
}

# Set up pacman & keyring
pacman_setup(){
	while [[ -e /var/lib/pacman/db.lck ]]; do
		echo "Waiting for pacman database to become available..."
		sleep 5
	done
	sed '7iServer = https://arch.zotan.services/$repo/os/$arch\n' /etc/pacman.d/mirrorlist > /etc/pacman.d/mirrors
	mv /etc/pacman.d/mirrors /etc/pacman.d/mirrorlist
	pacman -Sy --needed --noconfirm archlinux-keyring
	pacman -S --needed --noconfirm arch-install-scripts
	echo "Waiting for pacman keyring to enter a consistent state..."
	sleep 5
	pacman-key --populate
	if [ ! -f /usr/bin/wget ]; then
		pacman -S --needed --noconfirm wget libnewt
	fi
}

# Create disk partitions
partition_disk(){
	parted -s $disk mklabel gpt
	if [[ $efi -eq 1 ]]; then
		sgdisk $disk -n=1:0:+1024M -t=1:ef00
		sgdisk $disk -n=2:0:-$swapsize
		sgdisk $disk -n=3:0:0 -t=2:8200
	else
		sgdisk $disk -n=1:0:+1M -t=1:ef02
		sgdisk $disk -n=2:0:-$swapsize
		sgdisk $disk -n=3:0:0 -t=2:8200
	fi

	# Special naming for eMMC and NVME devices
	if [[ "${disk::8}" == "/dev/nvm" || "${disk::8}" == "/dev/mmc" ]]; then
	  bootdev=$disk"p1"
	  rootdev=$disk"p2"
	  swapdev=$disk"p3"
	else
	  bootdev=$disk"1"
	  rootdev=$disk"2"
	  swapdev=$disk"3"
	fi

	export bootdev
	export rootdev
	export swapdev

	# Format ESP to fat32
	if [[ $efi -eq 1 ]]; then
		mkfs.fat $bootdev
	fi
}

format_root(){
	if [[ "$luks" == "true" ]]; then
		format_root_luks
		return
	fi

	mkswap $swapdev # format swap
	mkfs.btrfs -f $rootdev # format root to btrfs
	mount $rootdev /mnt
	btrfs subvolume create /mnt/@ # new root subvolume
	btrfs subvolume set-default /mnt/@ # set as mount-default to prevent boot failures
	btrfs subvolume create /mnt/@snapshots # new snapshot subvolume
	mkdir -p /mnt/@/var/cache/pacman # create directory so next cmd works
	btrfs subvolume create /mnt/@/var/cache/pacman/pkg # exclude pacman cache from snapshots
	umount /mnt
	mount $rootdev -o subvol=@ /mnt # remount with new root
	mkdir /mnt/.snapshots
	mount $rootdev -o subvol=@snapshots /mnt/.snapshots # mount snapshots as /.snapshots in new root
}

format_root_luks(){
	echo "$lukspass" | cryptsetup -y -v luksFormat $rootdev # setup LUKS partition
	echo "$lukspass" | cryptsetup open $rootdev cryptroot # unlock it
	mkfs.btrfs -f /dev/mapper/cryptroot # format root to btrfs
	mount /dev/mapper/cryptroot /mnt
	btrfs subvolume create /mnt/@ # new root subvolume
	btrfs subvolume set-default /mnt/@ # set as mount-default to prevent boot failures
	btrfs subvolume create /mnt/@snapshots # new snapshots subvolume
	mkdir -p /mnt/@/var/cache/pacman
	btrfs subvolume create /mnt/@/var/cache/pacman/pkg # exclude pacman cache from snapshots
	umount /mnt
	mount /dev/mapper/cryptroot -o subvol=@ /mnt # remount with new root
	mkdir /mnt/.snapshots
	mount /dev/mapper/cryptroot -o subvol=@snapshots /mnt/.snapshots # mount snapshots as /.snapshots in new root
}

swapsetup(){
	if [[ "$luks" == "true" ]]; then
		# setup encrypted swap
		swapuuid=$(blkid -o value -s PARTUUID $swapdev)
		echo "swap PARTUUID=$swapuuid /dev/urandom swap,cipher=aes-cbc-essiv:sha256,size=256" >> /mnt/etc/crypttab
	else
		swapon $swapdev
	fi
}

# sets hostname, keymap, locale, timezone, root password
basic_postinstall(){
	echo "$hostname" > /mnt/etc/hostname
	echo "KEYMAP=$keylayout" > /mnt/etc/vconsole.conf
	echo "EDITOR=nano" >> /mnt/etc/environment
	echo "COLORTERM=truecolor" >> /mnt/etc/environment

	locale=en_US
	echo "LANG=$locale.UTF-8" > /mnt/etc/locale.conf
	sed -i '/'$locale'.UTF-8/s/^#//g' /mnt/etc/locale.gen
	sed -i 's/<U002E> IGNORE/<U002E> <RES-1>/g' /mnt/usr/share/i18n/locales/iso14651_t1_common
	archchroot locale-gen

	sed -i 's%#Color%Color%g' /mnt/etc/pacman.conf
	sed -i 's%#ParallelDownloads %ParallelDownloads %g' /mnt/etc/pacman.conf

	wget -O /mnt/usr/share/libalpm/hooks/locale-fix.hook ztn.sh/archx-resources/locale-fix.hook

	ln -sf /usr/share/zoneinfo/Europe/Berlin /mnt/etc/localtime
	archchroot "hwclock --systohc --utc"

	if [[ $unattended == "true" ]]; then
		arch-chroot /mnt /bin/bash -c "echo 'root:$password' | chpasswd -e"
	else
		arch-chroot /mnt /bin/bash -c "echo -e '$password\n$password' | passwd root"
	fi

	if [[ -s /root/.ssh/authorized_keys ]]; then
		mkdir -p /mnt/root/.ssh
		cp /root/.ssh/authorized_keys /mnt/root/.ssh/authorized_keys
	fi

	if [[ -n $cinetwork ]]; then
		set +e # we briefly need errors ignored
		cp /etc/systemd/network/??-cloud-init-*.link /mnt/etc/systemd/network || : # ignore failures because file doesn't exist
		cp /etc/systemd/network/??-cloud-init-*.network /mnt/etc/systemd/network || : # ignore failures because file doesn't exist
		cat /mnt/etc/systemd/network/??-cloud-init-*.network | grep -E 'DNS|Domains' | sed 's/DNS=/nameserver /g' | sed 's/Domains=/search /g' >> /mnt/etc/resolv.conf
		set -e # reenable exit-on-error

		# Fix up multiple match clauses generated by borked cloud-init
		for f in /mnt/etc/systemd/network/??-cloud-init-*.network; do
			# Check if [Match] section contains MACAddress
			cat "$f" | grep "\[Match\]" --after-context 999 | sed -z 's/\n\n/.*/\n/g' | grep -q "MACAddress="
			if [[ $? -eq 0 ]]; then
				# Remove Name= match clause
				sed -z -i 's/Name=.*?\n//g' "$f"
			fi
		done

		archchroot "systemctl enable systemd-networkd"
	fi
}

# sets up fstab, initramfs as well as encrypted swap if LUKS is enabled
setup_initramfs(){
	partprobe $disk # make sure the kernel has the correct device uuids
	genfstab -U -p /mnt > /mnt/etc/fstab
	if [[ "$luks" == "true" ]]; then
		echo "/dev/mapper/swap	none swap defaults 0 0" >> /mnt/etc/fstab
		sed -i "s/HOOKS=(base udev autodetect modconf block filesystems keyboard fsck)/HOOKS=(base udev autodetect keyboard keymap consolefont modconf block encrypt filesystems fsck)/g" /mnt/etc/mkinitcpio.conf
		archchroot "mkinitcpio -p linux"
	fi

	# add nvme module to initramfs if rootdevice is on a nvme drive
	if [ "${disk::8}" == "/dev/nvm" ]; then
		sed -i "s/MODULES=()/MODULES=(nvme)/g" /mnt/etc/mkinitcpio.conf
		archchroot "mkinitcpio -p linux"
	fi
}

# installs either refind or grub
install_bootloader(){
	if [[ "$efi" -eq 1 ]]; then
		install_refind
	else
		install_grub
	fi
}

install_refind(){
	pacstrap /mnt refind
	archchroot "refind-install --usedefault $bootdev"
	rootuuid=$(blkid -s UUID -o value $rootdev)

	if [[ -n $consoleboot ]]; then
		cmdline="rw add_efi_memmap $consoleboot"
	else
		cmdline="rw add_efi_memmap"
	fi

	if [[ "$luks" == "true" ]]; then
		echo "\"Arch Linux         \" \"cryptdevice=UUID=$rootuuid:cryptroot root=/dev/mapper/cryptroot $cmdline fbcon=nodefer quiet\"" > /mnt/boot/refind_linux.conf
		echo "\"Arch Linux Verbose \" \"cryptdevice=UUID=$rootuuid:cryptroot root=/dev/mapper/cryptroot $cmdline fbcon=nodefer\"" >> /mnt/boot/refind_linux.conf
		echo "\"Arch Linux Fallback\" \"cryptdevice=UUID=$rootuuid:cryptroot root=/dev/mapper/cryptroot $cmdline initrd=/initramfs-linux-fallback.img fbcon=nodefer quiet\"" >> /mnt/boot/refind_linux.conf
		echo "\"Arch Linux Terminal\" \"cryptdevice=UUID=$rootuuid:cryptroot root=/dev/mapper/cryptroot $cmdline systemd.unit=multi-user.target fbcon=nodefer quiet\"" >> /mnt/boot/refind_linux.conf
	else
		echo "\"Arch Linux         \" \"root=UUID=$rootuuid $cmdline quiet\"" > /mnt/boot/refind_linux.conf
		echo "\"Arch Linux Verbose \" \"root=UUID=$rootuuid $cmdline\"" >> /mnt/boot/refind_linux.conf
		echo "\"Arch Linux Fallback\" \"root=UUID=$rootuuid $cmdline initrd=/initramfs-linux-fallback.img quiet\"" >> /mnt/boot/refind_linux.conf
		echo "\"Arch Linux Terminal\" \"root=UUID=$rootuuid $cmdline systemd.unit=multi-user.target quiet\"" >> /mnt/boot/refind_linux.conf
	fi

	sed -i 's/timeout 20/timeout 5/g' /mnt/boot/EFI/BOOT/refind.conf
	sed -i 's/install, shell, bootorder, gdisk, memtest, mok_tool, apple_recovery, windows_recovery, about, //g' /mnt/boot/EFI/BOOT/refind.conf
	sed -i 's/#use_graphics_for osx,linux/use_graphics_for osx,linux/g' /mnt/boot/EFI/BOOT/refind.conf

	wget ztn.sh/archx-resources/vmlinuz-linux.png -O /mnt/boot/vmlinuz-linux.png
	wget ztn.sh/archx-resources/refind-theme.tar -O /mnt/tmp/refind-theme.tar
	tar xvf /mnt/tmp/refind-theme.tar -C /mnt/boot/EFI/BOOT
	rm /mnt/tmp/refind-theme.tar
	echo "include refind-theme-regular/theme.conf" >> /mnt/boot/EFI/BOOT/refind.conf
}

install_grub(){
	pacstrap /mnt grub
	mkdir /mnt/boot/grub
	if [[ -n $consoleboot ]]; then
		sed -i 's/GRUB_CMDLINE_LINUX=""/GRUB_CMDLINE_LINUX=\"'$consoleboot'\"/g' /mnt/etc/default/grub
	fi
	archchroot "grub-mkconfig -o /boot/grub/grub.cfg"
    archchroot "grub-install --target=i386-pc --recheck $disk"
}

# runs postinstall of selected profile
profile_postinstall(){	
	if [[ "$profile" == "cli" ]]; then
		postinstall_cli
	elif [[ "$profile" == "i3lite" ]]; then
		postinstall_i3
	elif [[ "$profile" == "kde" ]]; then
		postinstall_kde
	elif [[ "$profile" == "gnome" ]]; then
		postinstall_gnome
	fi
	archchroot "btrfs subvolume snapshot / /.snapshots/postinstall"
}

# installs git, entropy harvesting daemon, ssh, neofetch and htop
# adds the destiny repo to pacman
# adds the user & sets the password
# enables network
# creates backup snapshot
postinstall_cli(){
	# run this entire thing in new root
	archchroot "/bin/bash" <<"EOS"
	set -eo pipefail

	curl https://share.zotan.services/repo.sh | bash
	killall gpg-agent
	pacman -Syu --needed --noconfirm git haveged neofetch htop dialog zsh kernel-modules-hook nftables yay
	systemctl enable haveged sshd

	sed -i 's%#PasswordAuthentication yes%PasswordAuthentication no%g' /etc/ssh/sshd_config

	systemctl mask systemd-resolved

	systemctl enable linux-modules-cleanup
	systemctl enable systemd-timesyncd

	groupadd sudo -g 666
	echo "%sudo ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers

	cat /etc/makepkg.conf | sed "s/xz -c -z -)/xz -c -z - --threads=0)/g" > /tmp/makepkg.conf; mv /tmp/makepkg.conf /etc/makepkg.conf

	useradd "$user"
	if [[ $unattended == "true" ]]; then
		echo "$user:$password" | chpasswd -e
	else
		echo -e "$password\n$password" | passwd "$user"
	fi
	usermod -aG sudo "$user"
	usermod -aG adm "$user"
	mkdir /home/"$user"
	chown "$user":"$user" /home/"$user"

	if [[ -s /root/.ssh/authorized_keys ]]; then
		mkdir -p /home/$user/.ssh
		cp /root/.ssh/authorized_keys /home/$user/.ssh/authorized_keys
		chown $user:$user /home/$user/.ssh/authorized_keys
	fi

	if [[ -z $cinetwork ]]; then
		systemctl enable dhcpcd
	fi

	chsh -s /bin/zsh $user
	chsh -s /bin/zsh root
	wget share.zotan.services/prezto.sh -O /tmp/prezto.sh
	sudo -u $user zsh /tmp/prezto.sh
	zsh /tmp/prezto.sh

	btrfs subvolume snapshot / /.snapshots/basesystem

EOS
}

postinstall_xorg(){
	postinstall_cli
	archchroot "/bin/bash" <<"EOS"
	set -eo pipefail
	pacman -S --needed --noconfirm xorg-server xorg-drivers ttf-opensans ttf-dejavu ttf-hack ttf-liberation networkmanager
EOS
	if [[ "$keylayout" == "us" ]]; then
		return
	fi
cat <<EOF > /mnt/etc/X11/xorg.conf.d/00-keyboard.conf
Section "InputClass"
    Identifier "system-keyboard"
    MatchIsKeyboard "on"
    Option "XkbLayout" "de"
    Option "XkbModel" "pc105"
    Option "XkbVariant" "deadacute"
EndSection
EOF
}

postinstall_i3(){
	postinstall_xorg
	archchroot "/bin/bash" <<"EOS"
	set -eo pipefail
	pacman -S --needed --noconfirm i3-wm polybar archlinux-themes-sddm gnome-icon-theme gnome-icon-theme-symbolic gnome-icon-theme-extras adwaita-icon-theme alacritty sddm betterlockscreen
	systemctl enable sddm
	echo -e "[Autologin]\nRelogin=false\nSession=\nUser=\n\n[General]\nHaltCommand=/usr/bin/systemctl poweroff\nRebootCommand=/usr/bin/systemctl reboot\n\n[Theme]\nCurrent=archlinux-simplyblack\nCursorTheme=Adwaita\n\n[Users]\nMaximumUid=60000\nMinimumUid=1000" > /etc/sddm.conf
	systemctl enable betterlockscreen@$user
	systemctl disable dhcpcd
	systemctl enable NetworkManager

	# customizations

	pacman -S --needed --noconfirm google-chrome acpi insync rclone neofetch ccid libusb-compat pcsclite ncdu aria2 noto-fonts noto-fonts-cjk noto-fonts-extra noto-fonts-emoji-apple wireguard-tools p7zip papirus-icon-theme telegram-desktop sublime-text-4 siji-git bluez bluez-utils \
		dunst etcher-bin blueman bluez-tools btrbk cli-visualizer cronie evince exfat-utils flameshot freerdp remmina geeqie gimp gnome-themes-extra idevicerestore-git iftop jq syncthing mpv lxappearance lxsession \
		mediainfo mumble nautilus net-tools network-manager-applet nitrogen nfs-utils nmap ntfs-3g openssl-1.0 parcellite pasystray pavucontrol platformio postman-bin pulseaudio-alsa pulseaudio-bluetooth pulseaudio-zeroconf python-pip rclone rofi solaar spotify \
		sshuttle topgrade xorg-xrdb youtube-dl yubikey-manager yubikey-manager-qt gnome-keyring xorg-xinput libldac openbsd-netcat

	systemctl enable cronie
	systemctl enable libvirtd
	systemctl enable libvirt-guests

	wget https://raw.githubusercontent.com/Yubico/libu2f-host/master/70-u2f.rules -O /etc/udev/rules.d/70-u2f.rules
	echo 'ACTION=="add", SUBSYSTEM=="usb", ENV{ID_VENDOR_ID}=="1050", ENV{ID_MODEL_ID}=="0116|0111", MODE="660", GROUP="scard"' > 71-gnupg-ccid.rules
	mv 71-gnupg-ccid.rules /etc/udev/rules.d/71-gnupg-ccid.rules
	systemctl enable pcscd.socket
	sudo -u $user dbus-launch gsettings set org.gnome.desktop.interface icon-theme 'Papirus'
	sudo -u $user dbus-launch gsettings set org.gnome.desktop.interface gtk-theme 'Adwaita-dark'
	sudo -u $user dbus-launch gsettings set org.gnome.desktop.wm.preferences theme 'Adwaita-dark'
	echo '--force-dark-mode' > /home/$user/.config/chrome-flags.conf
	wget https://ztn.sh/archx-resources/fontconfig -O /etc/fonts/local.conf

	mkdir -p /etc/btrbk
	wget https://ztn.sh/archx-resources/btrbk.conf -O /etc/btrbk/btrbk.conf

	sudo -u $user mkdir -p /home/$user/.config/i3
	sudo -u $user wget https://ztn.sh/archx-resources/i3_config -O /home/$user/.config/i3/config

	sudo -u $user mkdir -p /home/$user/.config/polybar
	sudo -u $user wget https://ztn.sh/archx-resources/launch_polybar.sh -O /home/$user/.config/polybar/launch.sh
	chmod +x /home/$user/.config/polybar/launch.sh

	sudo -u $user mkdir -p /home/$user/.config/alacritty
	sudo -u $user wget https://ztn.sh/archx-resources/alacritty.yml -O /home/$user/.config/alacritty/alacritty.yml

	sudo -u $user mkdir -p /home/$user/.config/flameshot
	sudo -u $user wget https://ztn.sh/archx-resources/flameshot.ini -O /home/$user/.config/flameshot/flameshot.ini

	sudo -u $user mkdir -p /home/$user/.config/mpv
	sudo -u $user wget https://ztn.sh/archx-resources/mpv.conf -O /home/$user/.config/mpv/mpv.conf

	sudo -u $user mkdir -p /home/$user/.config/sublime-text-3/Packages/User
	sudo -u $user wget https://ztn.sh/archx-resources/Preferences.sublime-settings -O /home/$user/.config/sublime-text-3/Packages/User/Preferences.sublime-settings
	sudo -u $user wget https://ztn.sh/archx-resources/Default_Linux.sublime-keymap -O /home/$user/.config/sublime-text-3/Packages/User/Default\ \(Linux\).sublime-keymap

	sudo -u $user mkdir -p /home/$user/.config/dunst
	sudo -u $user wget https://ztn.sh/archx-resources/dunstrc -O /home/$user/.config/dunst/dunstrc

	sudo -u $user mkdir -p /home/$user/.config/parcellite
	sudo -u $user wget https://ztn.sh/archx-resources/parcellitec -O /home/$user/.config/parcellite/parcelliterc

	sudo -u $user mkdir -p /home/$user/.config/gtk-3.0
	sudo -u $user wget https://ztn.sh/archx-resources/gtk3-settings.ini -O /home/$user/.config/gtk-3.0/settings.ini

	sudo -u $user mkdir -p /home/$user/.config/rofi
	mkdir -p /usr/share/rofi/themes/
	sudo -u $user wget https://ztn.sh/archx-resources/rofi_config -O /home/$user/.config/rofi/config
	wget https://ztn.sh/archx-resources/flat-orange.rasi -O /usr/share/rofi/themes/flat-orange.rasi

	mkdir -p /var/spool/cron

	echo 'export COLORTERM=truecolor' >> /etc/profile
	echo 'export EDITOR=nano' >> /etc/profile
	echo '@hourly btrbk run -v' >> /var/spool/cron/root
	echo 'Xcursor.size: 16' > /home/$user/.Xresources
	chown $user:$user /home/$user/.Xresources

	sudo -u $user wget https://ztn.sh/archx-resources/polybar_config -O /home/$user/.config/polybar/config

	mkdir -p /etc/X11/xorg.conf.d
	wget https://ztn.sh/archx-resources/10-monitor.conf -O /etc/X11/xorg.conf.d/10-monitor.conf
EOS
}

postinstall_kde(){
	postinstall_xorg
	archchroot "/bin/bash" <<"EOS"
	set -eo pipefail
	pacman -S --needed --noconfirm plasma plasma-meta konsole dolphin kdialog sddm
	systemctl enable sddm
	echo -e "[Autologin]\nRelogin=false\nSession=\nUser=\n\n[General]\nHaltCommand=/usr/bin/systemctl poweroff\nRebootCommand=/usr/bin/systemctl reboot\n\n[Theme]\nCurrent=breeze\nCursorTheme=Adwaita\n\n[Users]\nMaximumUid=60000\nMinimumUid=1000" > /etc/sddm.conf
	systemctl disable dhcpcd
	systemctl enable NetworkManager
EOS
}

postinstall_gnome(){
	postinstall_xorg
	archchroot "/bin/bash" <<"EOS"
	set -eo pipefail
	pacman -S --needed --noconfirm gnome gnome-extra
	systemctl enable gdm
	systemctl disable dhcpcd
	systemctl enable NetworkManager
EOS
}

### postinstall_zotan_gnome(){
### 	postinstall_gnome
### 	archchroot "/bin/bash" <<"EOS"
### 	sudo pacman -S --needed --noconfirm google-chrome acpi insync rclone neofetch ccid libusb-compat pcsclite ncdu aria2 noto-fonts noto-fonts-cjk noto-fonts-extra ttf-joypixels zsh texlive-most biber wireguard-tools networkmanager-wireguard-git p7zip papirus-icon-theme adapta-gtk-theme telegram-desktop sublime-text-nightly
### 	sudo wget https://raw.githubusercontent.com/Yubico/libu2f-host/master/70-u2f.rules -O /etc/udev/rules.d/70-u2f.rules
### 	echo 'ACTION=="add", SUBSYSTEM=="usb", ENV{ID_VENDOR_ID}=="1050", ENV{ID_MODEL_ID}=="0116|0111", MODE="660", GROUP="scard"' > 71-gnupg-ccid.rules
### 	sudo mv 71-gnupg-ccid.rules /etc/udev/rules.d/71-gnupg-ccid.rules
### 	sudo systemctl enable pcscd.socket
### 	sudo -u $user dbus-launch gsettings set org.gnome.desktop.interface icon-theme 'Papirus'
### 	sudo -u $user dbus-launch gsettings set org.gnome.desktop.interface gtk-theme 'Adwaita-dark'
### 	sudo -u $user dbus-launch gsettings set org.gnome.desktop.wm.preferences theme 'Adwaita-dark'
### 	echo '--force-dark-mode' > /home/$user/.config/chrome-flags.conf
### 	sudo wget https://gist.githubusercontent.com/lhaus/f857f10d5aac2b48a03f41e685f5109d/raw/16eba11e83648fa2a2f9ba7b5865f361e0f45247/fontconfig -O /etc/fonts/local.conf
### EOS
### }
### 
### postinstall_zotan_kde(){
### 	postinstall_kde
### 	archchroot "/bin/bash" <<"EOS"
### 	sudo pacman -S --needed --noconfirm google-chrome acpi insync rclone neofetch ccid libusb-compat pcsclite ncdu aria2 noto-fonts noto-fonts-cjk noto-fonts-extra ttf-joypixels zsh texlive-most biber wireguard-tools networkmanager-wireguard-git p7zip papirus-icon-theme adapta-gtk-theme telegram-desktop sublime-text-nightly
### 	sudo pacman -S --needed --noconfirm okular kleopatra spectacle libdbusmenu-glib libdbusmenu-gtk2 libdbusmenu-gtk3 appmenu-gtk-module ntfs-3g
### 	sudo wget https://raw.githubusercontent.com/Yubico/libu2f-host/master/70-u2f.rules -O /etc/udev/rules.d/70-u2f.rules
### 	echo 'ACTION=="add", SUBSYSTEM=="usb", ENV{ID_VENDOR_ID}=="1050", ENV{ID_MODEL_ID}=="0116|0111", MODE="660", GROUP="scard"' > 71-gnupg-ccid.rules
### 	sudo mv 71-gnupg-ccid.rules /etc/udev/rules.d/71-gnupg-ccid.rules
### 	sudo systemctl enable pcscd.socket  
### 	echo '--force-dark-mode' > /home/$user/.config/chrome-flags.conf
### 	sudo wget https://gist.githubusercontent.com/lhaus/f857f10d5aac2b48a03f41e685f5109d/raw/16eba11e83648fa2a2f9ba7b5865f361e0f45247/fontconfig -O /etc/fonts/local.conf
### EOS
### }

# Unmount all disks
unmount(){
	umount -R /mnt

	if [[ "$luks" == "true" ]]; then
		cryptsetup luksClose /dev/mapper/cryptroot
	else
		swapoff "$swapdev"
	fi
}

# ---HELPER FUNCTIONS---
confirm() {
    # call with a prompt string or use a default
    read -r -p "${1:-Are you sure? [y/N]} " response
    case "$response" in
        [yYzZ][eE][sS]|[yYzZ])
            true
            ;;
        *)
            false
            ;;
    esac
}

archchroot(){
  arch-chroot /mnt $1
}

main $@
