#!/bin/bash

ARCH=amd64
DEBIAN_VERSION=buster
DEB_ARCHIVE_KEYRING=http://deb.debian.org/debian/pool/main/d/debian-archive-keyring/debian-archive-keyring_2019.1_all.deb
DEB_DEBOOTSTRAP=http://deb.debian.org/debian/pool/main/d/debootstrap/debootstrap_1.0.114_all.deb
BOOT_DRIVE=/dev/sda

if [ "$UID" -ne 0 ]; then
    echo 'Needs to run as root.'
    exit 1
fi

wget "$DEB_ARCHIVE_KEYRING" "$DEB_DEBOOTSTRAP"
dpkg -i "$(basename "$DEB_ARCHIVE_KEYRING")" "$(basename "$DEB_DEBOOTSTRAP")"
rm "$(basename "$DEB_ARCHIVE_KEYRING")" "$(basename "$DEB_DEBOOTSTRAP")"
apt install -f

debootstrap --arch "$ARCH" "$DEBIAN_VERSION" /debian http://deb.debian.org/debian

for dir in /proc /sys /dev /dev/pts; do
    mount --bind "$dir" "/debian/$dir"
done

mkdir -p /debian/old_root
mount --bind / /debian/old_root

EFI_SYSTEM="$(df | grep /boot/efi | cut -d' ' -f1)"
umount /boot/efi

cp /etc/resolv.conf /etc/fstab /debian/etc

cat > /debian/install.sh <<EOF
apt-get install -y 'linux-image-$ARCH' grub-efi openssh-server rsync

sed -i -E 's/^(GRUB_CMDLINE_LINUX=")(.*")$/\1net.ifnames=0 biosdevname=0 \2/' /etc/default/grub

echo 'allow-hotplug eth0' > /etc/network/interfaces.d/eth0
echo 'iface eth0 inet dhcp' >> /etc/network/interfaces.d/eth0

mkdir /boot/efi
mount '$EFI_SYSTEM' /boot/efi

echo 'Set a root password:'
passwd

echo
mkdir /root/.ssh
echo 'Enter your SSH keys and finish with ^D:'
cat > /root/.ssh/authorized_keys

mkdir /old_root/old
mv old_root/* old_root/old

echo 'grub-efi-amd64 grub2/force_efi_extra_removable boolean true' | debconf-set-selections
grub-install '$BOOT_DRIVE'
update-grub

mkdir -p /boot/efi/EFI/boot
cp /boot/efi/EFI/debian/grubx64.efi /boot/efi/EFI/boot/bootx64.efi

rsync -ax bin boot etc home lib lib32 lib64 libx32 media mnt opt root sbin srv tmp usr var old_root/
EOF

chroot /debian /bin/bash /install.sh
reboot -f
