#!/bin/bash

set -x

ROOTFS=void-x86_64-ROOTFS-20230628.tar.xz

mkdir /VOID
cd /VOID
wget https://repo-default.voidlinux.org/live/current/$ROOTFS -O void-root.tgz
tar -xf void-root.tgz


cat << EOF > /VOID/takeover.sh
echo "Welcome to takeover!"

# first, fixup env (otherwise we break grub...)
export LANG=en_US.UTF-8
export LC_COLLATE=C

echo "nameserver 8.8.8.8" > /etc/resolv.conf

echo "# updating base config"
yes | xbps-install -Su xbps
yes | xbps-install -u
yes | xbps-install base-system rsync curl grub-x86_64-efi
yes | xbps-remove base-voidstrap
xbps-reconfigure -f glibc-locales

echo "# building fstab"

cat << FSTAB > /etc/fstab
LABEL=cloudimg-rootfs /         ext4  defaults,noatime 0 1
LABEL=UEFI            /boot/efi vfat  defaults 0 2
tmpfs                /tmp       tmpfs defaults,nosuid,nodev 0 0
FSTAB

echo "# configuring grub"
# needed to have console working

cat << GRUB_EOF >> /etc/default/grub
GRUB_TERMINAL_OUTPUT=console
GRUB_CMDLINE_LINUX_DEFAULT="console=tty1 console=ttyS0"
GRUB_EOF

grub-install --target=x86_64-efi --efi-directory=/boot/efi --bootloader-id="Void"


echo "# finalizing installation"
xbps-reconfigure -fa

echo "# setting up services and things"
( cd /etc/runit/runsvdir/current
  ln -s /etc/sv/dhcpcd .
  ln -s /etc/sv/sshd   .
  ln -s /etc/sv/agetty-ttyS0 .
)

echo "# Setting up hostname and user"
echo "void-oracle" > /etc/hostname

useradd adrian
( cd /home/adrian
  mkdir .ssh
  curl -o .ssh/authorized_keys https://github.com/adrian-bl.keys
  chown -R adrian:adrian .ssh
  chmod 0700 .ssh
  chmod 0644 .ssh/authorized_keys
)


echo "# swapping system"
( cd /OLD
  mkdir JUNK
  mv bin boot etc home lib lib32 lib64 libx32 media mnt opt root sbin snap srv tmp usr var JUNK
)

( cd /
  rsync -av --progress -X bin boot etc home lib lib32 lib64 media mnt opt root sbin tmp usr var OLD/
)


sync
echo u > /proc/sysrq-trigger
sync
echo b > /proc/sysrq-trigger
EOF


echo "preparing mounts"
mount -t proc  none /VOID/proc
mount -t sysfs none /VOID/sys
mount --rbind  /dev /VOID/dev
mount --rbind  /run /VOID/run
mkdir /VOID/OLD
mount --bind / /VOID/OLD

mkdir /VOID/boot/efi
rm -rf /boot/efi/EFI
umount /boot/efi
mount LABEL=UEFI /VOID/boot/efi

echo "switching into chroot"
chmod +x /VOID/takeover.sh
chroot /VOID ./takeover.sh
