#!/usr/bin/env bash

set -ex

DISK=$1
HOSTNAME=$2
EFI=$3
if [[ "$HOSTNAME" = "efi" ]]; then
    unset HOSTNAME
    EFI=efi
fi
[[ -z "$HOSTNAME" ]] && HOSTNAME=$(host $(ip addr | grep 'inet 147.251' | cut -d/ -f1 | sed 's/.*inet //') | sed 's/^.* \([a-z0-9]*\).fi.muni.cz.*$/\1/')
echo "installing $HOSTNAME to $DISK"

getpart() {
    if [[ -b ${1}${2} ]]; then
        printf ${1}${2}
    else
        printf ${1}p${2}
    fi
}

if [[ "$EFI" = "efi" ]]; then
# new partition 2 spanning rest of the disk
#   set it to type Linux LVM
# LVM type partition
sed -re 's/^[ \t]+([\+0-9a-zA-Z]*)[ \t]*#.*$/\1/' << EOF | fdisk $DISK
	g # GPT partition table
	n # new partion
	  # partition 1
	  # default start
	+512M # 512MB
	t # set type
	1 # EFI system
	n # new partition
	  # partition 2
	  # default start
	  # default end
	t # set type
	2 # for partition 2
	31 # LVM
	p # print
	w # write
EOF
    PARTN=2
    mkfs.fat -F32 $(getpart $DISK 1)
else
# MBR/DOS table
# new partition 1 spanning full disk
# LVM type partition
echo -e 'o\n' \
	'n\np\n1\n\n\n' \
	't\n8e\n' \
	'p\n' \
	'w\n' \
	| sed 's/ //g' | fdisk $DISK
    PARTN=1
fi
PART=$(getpart $DISK $PARTN)
pvcreate $PART
VG=vg.$HOSTNAME
vgcreate $VG $PART
lvcreate -L128G -n root $VG
ROOTD=/dev/$VG/root
mkfs.xfs -m reflink=1 $ROOTD
ROOT=/mnt/root
mkdir -p $ROOT
mount $ROOTD $ROOT
if [[ "$EFI" = "efi" ]]; then
	mkdir -p $ROOT/boot/efi
	mount $(getpart $DISK 1) $ROOT/boot/efi
fi
debootstrap stable $ROOT http://ftp.cz.debian.org/debian/
git clone https://gitlab.fi.muni.cz/paradise/deploy $ROOT/root/deploy
genfstab -U $ROOT > $ROOT/etc/fstab
echo $HOSTNAME > $ROOT/etc/hostname
arch-chroot $ROOT /bin/bash /root/deploy/debootstrap-stage2 $DISK $EFI
