#!/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

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

cat > /debian/install.sh <<EOF
apt-get install -y 'linux-image-$ARCH' grub 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

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

grub-install '$BOOT_DRIVE'
update-grub

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
