#!/bin/bash

### Variables:
# $dsks = whole lsblk output (e.g. "sda 1,0T, sdb ..")
# $disk = only selected disk (e.g. "sdc 500G")
# $dev  = selected disk without size (e.g. "sdd")
# $main = main partition (e.g. "sde2")
# $szmn = size of the main partition (e.g. "50")
# szrt = size of root LVM volume
# $boot = boot partition (e.g. "sdf1")
# $host = hostname
# $user = username
# $pwur = user password
# $pwrt = root password
# $pwcr = encryption password
# $pwfr = password first
# $pwsc = password second

# Friendly introduction.
echo "Welcome to the Arch Linux installation script!"
echo "This script will ERASE ALL DATA on the partition you will choose next!"
echo
read -p "Do you want to continue? Type [Y]es or [N]o. " -n 1 -r
echo    # (optional) move to a new line
if [[ ! $REPLY =~ ^[Yy]$ ]]
then
    exit 1
fi
echo

# Selecting disk.
echo "1. PARTITIONING"
echo "Please select a disk to partition:"
echo

# Don't separate values by space.
IFS=$'\n'

# Set variable containing name and size of all disks.
dsks=( $(lsblk -d | tail -n+2 | awk '{print $1" "$4}') )

# Declare the array.
declare -a dsks

# Select value on array.
select dev in ${dsks[*]}
do

break
done
echo

# Separate values by spaces.
IFS=' '

# Create new variable of selection.
array=($dev)
dev="${array[0]}"
szmn="${array[1]%?}"

# Setting partition size.
echo "Your system partition has a size of $szmn GB."
echo "What size should your root volume have (GB)?"
echo "The rest will be used for your home volume."
read szrt
echo

echo "2. ENCRYPTION"
echo

# Setting encryption password.
echo "Choose a strong password for encrypting the primary partition:"
while [ -z "$pwcr" ]; do
echo "Please enter a password: "
read -s pwfr
read -s -p "Retype a password: " pwsc
if [ $pwfr == $pwsc ];
then
  pwcr=$pwfr
  echo
  echo "Both passwords are the same. Continuing.."
else
  echo
  echo "You have entered different passwords. Try again.."
  echo
continue
fi
break
done
echo

echo "3. HOSTNAME"
echo

# Setting hostname.
echo "Before installing the system, please enter a hostname:"
read host
echo

echo "4. ROOT PASSWORD"
echo

# Setting root password.
echo "Choose a password for the root account:"
while [ -z "$pwrt" ]; do
echo "Please enter a password: "
read -s pwfr
read -s -p "Retype a password: " pwsc
if [ $pwfr == $pwsc ];
then
  pwrt=$pwfr
  echo
  echo "Both passwords are the same. Continuing.."
else
  echo
  echo "You have entered different passwords. Try again.."
  echo
continue
fi
break
done
echo

echo "4. USER"
echo

# Setting username
echo "Please enter a username:"
read user
echo

# Setting user password.
echo "Also please choose a password for your user:"
while [ -z "$pwur" ]; do
echo "Please enter a password: "
read -s pwfr
read -s -p "Retype a password: " pwsc
if [ $pwfr == $pwsc ];
then
  pwur=$pwfr
  echo
  echo "Both passwords are the same. Continuing.."
else
  echo
  echo "You have entered different passwords. Try again.."
  echo
continue
fi

break
done
echo

echo "5. INSTALLING SYSTEM.."
echo

# Starting partitioning.
echo "Partitioning /dev/$dev.."
echo

# Clearing partition table of selected disk.
echo "Clearing existing partitioning table."
sgdisk -Z /dev/$dev &&
echo

# Creating BIOS boot partition.
echo "Creating BIOS boot partition of 1 MB."
sgdisk -n 1:0:+1M /dev/$dev &&
echo

# Creating boot partition.
echo "Creating boot partition of 256 MB."
sgdisk -n 2:0:+256M /dev/$dev &&
echo

# Setting type for EFI.
echo "Marking partition as boot."
sgdisk -t 1:ef02 /dev/$dev &&
echo

# Creating system partition.
echo "Creating system partition of $szmn GB."
sgdisk -n 3:0:0 /dev/$dev
echo

# Print partitions.
echo "This is your new partition table:"
lsblk | grep "$dev"
echo

# Get new variable.
main=${dev}3

# Encrypting partition.
echo "Encrypting system partition. This might take a while."
echo
echo -en "$pwcr\n$pwcr" | cryptsetup -c aes-xts-plain -s 512 luksFormat /dev/$main &&
echo "Partition successfully encrypted."
echo

# Opening encrypted partition and mounting at /dev/mapper/lvm.
echo "Decrypting.. This also might take a while."
echo
echo -en "$pwcr\n$pwcr" | cryptsetup luksOpen /dev/$main lvm &&
echo "Partition successfully opened."
echo

lsblk | grep "$dev"
echo

# Creating physical volume.
echo "Creating physical volume."
pvcreate /dev/mapper/lvm &&
echo

# Creating volume group "main".
echo "Creating volume group."
vgcreate main /dev/mapper/lvm &&
echo

# Creating logical volumes.
echo "Creating logical volumes for root and home."
lvcreate -L ${szrt}G -n root main &&
lvcreate -l 100%FREE -n home main &&
echo "Logical volumes successfully created."
echo
 
echo "Creating the filesystem."
boot=${dev}2
mkfs.fat -F 32 -n BIOS /dev/$boot &&
echo "Filesystem for boot successfully created."
echo
 
mkfs.ext4 -L root /dev/mapper/main-root &&
echo "Filesystem for root successfully created."
echo 
 
mkfs.ext4 -L home /dev/mapper/main-home &&
echo "Filesystem for home successfully created."
echo

echo "Mounting.."
mount /dev/mapper/main-root /mnt &&
mkdir /mnt/boot &&
mkdir /mnt/home &&
mount /dev/$boot /mnt/boot &&
mount /dev/mapper/main-home /mnt/home &&
echo "Mounting complete."
echo

#lsblk | grep "$dev"
lsblk
echo

# Updating mirrors using reflector.
echo "Updating mirrors.."
reflector --verbose --latest 10 --country Germany --age 24 --protocol https --sort rate --save /etc/pacman.d/mirrorlist &&
#reflector --verbose --latest 10 --age 24 --protocol https --sort rate --save /etc/pacman.d/mirrorlist &&
echo "Done."
echo

echo "Updating keyring.."
pacman -Sy archlinux-keyring --noconfirm &&
echo "Done."
echo

# Installing base system.
echo "Installing basic packages.."
#pacstrap /mnt base base-devel firefox konsole linux linux-firmware linux-zen lvm2 networkmanager nano plasma-desktop sddm sddm-kcm && 
pacstrap /mnt base firefox grub konsole linux linux-firmware linux-zen lvm2 nano networkmanager plasma-desktop sddm sddm-kcm sudo &&
echo "Base system installed."
echo

# Generating fstab.
echo "Generating fstab."
genfstab -Up /mnt > /mnt/etc/fstab &&
echo "Done."
echo

# Setting hostname.
echo "Setting hostname"
echo $host > /mnt/etc/hostname &&
echo "Done."
echo

# Setting locale.
echo "Setting and generating locale."
#localegen=$(cat /mnt/etc/locale.gen)
cat <<EOF > /mnt/etc/locale.gen
en_US.UTF-8 UTF-8
de_DE.UTF-8 UTF-8
EOF
#echo "${localegen}" >>/mnt/etc/locale.gen
arch-chroot /mnt locale-gen
echo "LANG=en_US.UTF-8" >/mnt/etc/locale.conf &&
#echo "LANG=de_DE.UTF-8" >/mnt/etc/locale.conf
echo "KEYMAP=de-latin1" > /mnt/etc/vconsole.conf &&
echo "Done."
echo

# Set X locale and keyboard alyout.
echo "Setting locale and keyboard layout."
arch-chroot /mnt localectl --no-convert set-keymap de-latin1-nodeadkeys &&

cat << EOF > /mnt/etc/X11/xorg.conf.d/00-keyboard.conf &&
# Written by systemd-localed(8), read by systemd-localed and Xorg. It's
# probably wise not to edit this file manually. Use localectl(1) to
# instruct systemd-localed to update it.
Section "InputClass"
        Identifier "system-keyboard"
        MatchIsKeyboard "on"
        Option "XkbLayout" "de"
        Option "XkbModel" "pc105"
        Option "XkbVariant" "deadgraveacute"
EndSection
EOF
echo "Done."
echo

# Editing mkinitcpio.conf.
echo "Editing /etc/mkinitcpio.conf."
sed -i '7s/.*/MODULES=(ext4)/' /mnt/etc/mkinitcpio.conf &&
sed -i '52s/.*/HOOKS=(base udev autodetect modconf block keyboard keymap encrypt lvm2 filesystems fsck shutdown)/' /mnt/etc/mkinitcpio.conf &&
echo "Done."
echo

# Creating inital ramdisk.
echo "Creating inital ramdisk for linux-zen."
arch-chroot /mnt mkinitcpio -p linux-zen &&
echo "Done."
echo

# Enable network and display manager.
echo "Enabling Networkmanager and display manager (sddm)."
arch-chroot /mnt systemctl enable NetworkManager sddm &&
echo "Done."
echo

# Set root password
echo "Setting root password:"
echo -en "$pwrt\n$pwrt" | arch-chroot /mnt passwd
echo "Done."
echo

# Install bootloader.
echo "Installing GRUB."
arch-chroot /mnt grub-install --target=i386-pc /dev/$dev &&
sed -i '7s|.*|GRUB_CMDLINE_LINUX="cryptdevice=/dev/'$main':lvm root=/dev/mapper/main-root"|' /mnt/etc/default/grub &&
sed -i '10s/.*/GRUB_PRELOAD_MODULES="part_gpt part_msdos lvm"/' /mnt/etc/default/grub &&
arch-chroot /mnt grub-mkconfig -o /boot/grub/grub.cfg &&
echo "Done."
echo

# Set bootloader entry.
#echo "Setting up bootloader."
#cat << EOF > /mnt/boot/loader/entries/arch.conf &&
#title   Arch Linux
#linux   /vmlinuz-linux-zen
##initrd  /amd-ucode.img 
#initrd  /intel-ucode.img
#initrd  /initramfs-linux-zen.img
#options cryptdevice=/dev/$main:lvm
#options root=/dev/mapper/main-root rw
#options lang=de locale=de_DE.UTF-8
#options init=/usr/lib/systemd/systemd
#options loglevel=3
#EOF

# Set username, password and group.
echo "Adding user."
arch-chroot /mnt useradd -m $user &&
echo -en "$pwur\n$pwur" | arch-chroot /mnt passwd $user &&
arch-chroot /mnt gpasswd -a $user wheel &&
sed -i '82s/.*/%wheel ALL=(ALL) ALL/' /mnt/etc/sudoers &&
echo "Done."
echo

# Enabling sddm auto-login.
echo "Enabling auto-login."
mkdir /mnt/etc/sddm.conf.d &&
cat << EOF > /mnt/etc/sddm.conf.d/autologin.conf
[Autologin]
User=$user
Session=plasma
EOF
echo "Done."
echo

# Unmounting and rebooting.
echo "Unmounting system."
umount /mnt/boot &&
umount /mnt/home &&
echo "Done."
echo

clear

echo "Installation finished!"
read -p "Press [Enter] to shut down, then remove the installation media and start your system."
poweroff
