#!/bin/bash

set -e # Exit on error

DEVICE=$1

[[ -z "${DEVICE}" ]]  && echo "Usage $0 /dev/sdX" && exit 1

udevadm info -n ${DEVICE} -q property
echo "Selected device is ${DEVICE}"
read -p "[Press enter to continue or CTRL+C to stop]"

echo "Umount ${DEVICE}"
umount ${DEVICE}* || true

echo "Set partition table to GPT (UEFI)"
parted ${DEVICE} --script mktable gpt

echo "Create EFI partition"
parted ${DEVICE} --script mkpart EFI fat16 1MiB 10MiB
parted ${DEVICE} --script set 1 msftdata on

echo "Create OS partition"
parted ${DEVICE} --script mkpart LINUX btrfs 10MiB 4GiB

echo "Format partitions"
mkfs.vfat -n EFI ${DEVICE}1
mkfs.btrfs -f -L LINUX ${DEVICE}2

ROOTFS_UUID=$(btrfs filesystem show ${DEVICE}2 | grep -Po "uuid: [a-f0-9-]+"|cut -c 7-44)
if [[ -z ${ROOTFS_UUID} ]]; then
echo "Rootfs UUID is <<${ROOTFS_UUID}>>"
echo "WARNING! BUG! The UUID is not set in the fstab. Either because this command failed (empty UUID above) or because of chroot scoping. Please fix it."
echo "Your OS will still be able to boot normally and remount the filesystem as RW but it could crash some apps like fsck"
read -p "[Press enter to continue or CTRL+C to stop]"
fi

echo "Mount OS partition"
ROOTFS="/tmp/installing-rootfs"
mkdir -p ${ROOTFS}
mount ${DEVICE}2 ${ROOTFS}

echo "Debootstrap system"
debootstrap --variant=minbase --arch amd64 buster ${ROOTFS} http://deb.debian.org/debian/

echo "Mount EFI partition"
mkdir -p ${ROOTFS}/boot/efi
mount ${DEVICE}1 ${ROOTFS}/boot/efi

echo "Get ready for chroot"
mount --bind /dev ${ROOTFS}/dev
mount -t devpts /dev/pts ${ROOTFS}/dev/pts
mount -t proc proc ${ROOTFS}/proc
mount -t sysfs sysfs ${ROOTFS}/sys
mount -t tmpfs tmpfs ${ROOTFS}/tmp

echo "Entering chroot, installing Linux kernel and Grub"
cat << EOF | chroot ${ROOTFS}
  set -e
  export HOME=/root
  export PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/sbin
  export DEBIAN_FRONTEND=noninteractive
  debconf-set-selections <<< "grub-efi-amd64 grub2/update_nvram boolean false"
  apt-get remove -y grub-efi grub-efi-amd64
  apt-get update
  apt-get install -y linux-image-generic linux-headers-generic grub-efi
  grub-install --target=x86_64-efi --efi-directory=/boot/efi --bootloader-id=debian --recheck --no-nvram --removable
  update-grub
EOF

echo "Install script based on dd"
cat << 'EOF' > ${ROOTFS}/usr/local/sbin/os-install
  #!/bin/bash

  set -e

  SOURCE=$1
  TARGET=$2
  # We write partitions until 4GiB = 4 * 1024^3 (https://en.wikipedia.org/wiki/Gibibyte)
  # In dd, M means 1048576 bytes = 1024^2 (man dd)
  # So we need to copy (4 * 1024^3) / (4 * 1024^2) = 0.5 * 1024 = 1024 blocks
  dd if=${SOURCE} of=${TARGET} bs=4M status=progress count=1030
  growpart ${TARGET} 2
  mount ${TARGET}2 /mnt
  btrfs filesystem resize max /mnt
  umount /mnt
  echo "you might want to run: btrfstune -u ${TARGET}2 but you will need to update the fstab"
  echo "you might want to change systemd machine UUID"
  echo "you might want to change /etc/systemd/network/en.network configuration"
EOF

chmod +x ${ROOTFS}/usr/local/sbin/os-install

echo "Entering chroot (bis), installing daemon"
cat << EOF | chroot ${ROOTFS}
  set -e
  export HOME=/root
  export PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/sbin
  export DEBIAN_FRONTEND=noninteractive

  # Set fstab
  echo "UUID=${ROOTFS_UUID} / btrfs defaults 0 0" > /etc/fstab

  # Install systemd and OpenSSH
  apt-get update
  apt-get install -y systemd openssh-server sudo btrfs-tools cloud-utils python 
  systemctl enable ssh

  # Enable systemd services
  systemctl enable systemd-networkd systemd-timesyncd systemd-resolved

  # Listen on any ethernet interface for DHCP
  tee /etc/systemd/network/en.network << EOG
[Match]
Name=en*

[Network]
DHCP=ipv4
EOG

  # Add SSH keys
  mkdir -p /root/.ssh
  tee /root/.ssh/authorized_keys << EOG
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDT1+H08FdUSvdPpPKdcafq4+JRHvFVjfvG5Id97LAoROmFRUb/ZOMTLdNuD7FqvW0Da5CPxIMr8ZxfrFLtpGyuG7qdI030iIRZPlKpBh37epZHaV+l9F4ZwJQMIBO9cuyLPXgsyvM/s7tDtrdK1k7JTf2EVvoirrjSzBaMhAnhi7//to8zvujDtgDZzy6aby75bAaDetlYPBq2brWehtrf9yDDG9WAMYJqp//scje/WmhbRR6eSdim1HaUcWk5+4ZPt8sQJcy8iWxQ4jtgjqTvMOe5v8ZPkxJNBine/ZKoJsv7FzKem00xEH7opzktaGukyEqH0VwOwKhmBiqsX2yN quentin@dufour.io
EOG
  
  echo "Done"
EOF

echo "Unmounting filesystems"
umount ${ROOTFS}/dev/pts
umount ${ROOTFS}/dev
umount ${ROOTFS}/proc
umount ${ROOTFS}/sys
umount ${ROOTFS}/tmp
umount ${ROOTFS}/boot/efi
umount ${ROOTFS}

echo "Done"
