#!/bin/sh
# Stage 1 installer. To be run in the live system after boot.
# Live system should be able to access the internet right after booting. The
# host needs to be set up this way (assuming this is a VM being set up).

diskdev="/dev/vda"
swapfile="/.swap"
swapsize="4G"
hostname="v20013"

rootpart="${diskdev}2"

b0=$(basename "$0")

# Not sure whether setting the correct time in the live system is necessary.
# It has just booted in the VM and its time is equal to that of the host.
#timedatectl set-ntp true

echo "$b0: Creating partitions on $diskdev ..."
# Clear partiton tables.
sgdisk -og $diskdev
# Create one BIOS boot partition of 512K. It is required for GRUB bootloader
# and Bhyve will need that to start the kernel.
sgdisk -n 1:2048:526335 -c 1:"BIOS Boot" -t 1:ef02 $diskdev
# Create Linux root filesystem partition using the rest of the available
# space, begining at the first MB.
sgdisk -n 2:526336:0 -c 2:"Linux Root" -t 2:8300 $diskdev

echo "$b0: Making EXT4 filesystem on $rootpart ..."
mkfs.ext4 -F $rootpart
mount $rootpart /mnt

echo "$b0: Creating swap file..."
fallocate -l $swapsize /mnt$swapfile
chmod 600 /mnt$swapfile
mkswap /mnt$swapfile
swapon /mnt$swapfile

echo "$b0: Installing packages..."
echo "Server = https://mirrors.niyawe.de/archlinux/\$repo/os/\$arch" > /etc/pacman.d/mirrorlist
echo "Server = https://mirror.chaoticum.net/arch/\$repo/os/\$arch" >> /etc/pacman.d/mirrorlist
echo "Server = https://mirror.f4st.host/archlinux/\$repo/os/\$arch" >> /etc/pacman.d/mirrorlist
echo "Server = https://mirror.ubrco.de/archlinux/\$repo/os/\$arch" >> /etc/pacman.d/mirrorlist
pacstrap /mnt base base-devel linux linux-firmware grub openssh python

echo "$b0: Generating fstab..."
genfstab -U /mnt >> /mnt/etc/fstab

echo "$b0: Setting time zone and locale..."
ln -sf /usr/share/zoneinfo/Europe/Berlin /mnt/etc/localtime
echo "en_US.UTF-8 UTF-8" > /mnt/etc/locale.gen
arch-chroot /mnt locale-gen
echo "LANG=en_US.UTF-8" > /mnt/etc/locale.conf

echo "$b0: Setting hostname..."
echo "$hostname" > /mnt/etc/hostname
echo "127.0.0.1 localhost" > /mnt/etc/hosts
echo "::1       localhost" >> /mnt/etc/hosts
dhcpcfg=$(cat <<EOT
[Match]
Name=en*

[Network]
DHCP=ipv4
EOT
)
echo "$dhcpcfg" > /mnt/etc/systemd/network/endhcp.network
arch-chroot /mnt systemctl enable systemd-networkd
ln -sf /run/systemd/resolve/stub-resolv.conf /mnt/etc/resolv.conf
arch-chroot /mnt systemctl enable systemd-resolved

echo "$b0: Installing bootloader..."
arch-chroot /mnt grub-install --target=i386-pc /dev/vda
arch-chroot /mnt grub-mkconfig -o /boot/grub/grub.cfg

echo "$b0: Enabling secure shell...."
mkdir /mnt/root/.ssh
echo 'ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBDi36GVhKJtzrBWofi8TZxQgAHLyj+sx/qFpYVkBYpUCocbHMTXFwRxQQJ7cbxombqqnvXwO+rLA1aB7AQ6Rbnk=' >> /mnt/root/.ssh/authorized_keys
arch-chroot /mnt systemctl enable sshd

echo "$b0: Cleaning up..."
swapoff -a
sync
umount /mnt

echo "$b0: Done."

