#!/usr/bin/env bash

set -e

# TODO: Somehow save progress of script, so reruns will continue at last finished step

main() {
	local arch
	local disk
	local hostname
	local part_data
	local part_efi
	local root_mount
	local mirror

	# TODO: Get user input and sysinfo
	arch="amd64"
	disk="virtio-91d379bc8b983339d0f2"
	hostname="testoo"
	root_mount="/mnt/gentoo"
	mirror="https://distfiles.gentoo.org"

	# Partition disk
	log "Partitioning disk $disk"
	cat <<-EOF | parted -a optimal "/dev/disk/by-id/$disk" >/dev/null 2>&1
	mklabel gpt
	mkpart esp 1 5130
	mkpart rootfs 5130 -1
	set 1 boot on
	quit
	EOF

	# Create filesystems
	log "Formatting ESP"
	mkfs.vfat -F32 "/dev/disk/by-id/$disk-part1" >/dev/null

	log "Formatting rootfs"
	zpool create -f \
		-O acltype=posixacl \
		-O compression=lz4 \
		-O dedup=off \
		-O relatime=on \
		-O xattr=sa \
		-R "$root_mount" \
		-m none \
		-o ashift=12 \
		-o "cachefile=/etc/zfs/${hostname}0.cache" \
		"${hostname}0" \
		"/dev/disk/by-id/$disk-part2"

	# Create datasets
	log "Creating ZFS datasets"
	zfs create -o mountpoint=none       "${hostname}0/rootfs"
	zfs create -o mountpoint=/          "${hostname}0/rootfs/gentoo"
	zfs create -o mountpoint=none       "${hostname}0/home"

	zpool set bootfs="${hostname}0/rootfs/gentoo" "${hostname}0"

	# Set up EFI partition
	mkdir -- "$root_mount/efi"
	mount "/dev/disk/by-id/$disk-part1" "$root_mount/efi"

	# Change to the root mount
	log "Changing workdir to $root_mount"
	mkdir -p -- "$root_mount"
	cd -- "$root_mount"

	# Unpack stage3
	log "Unpacking stage3"
	tarball="$(curl -q "$mirror/releases/$arch/autobuilds/current-stage3-$arch-systemd/latest-stage3-$arch-systemd.txt" | awk '/^stage3/ { print $1 }')"
	curl -q "$mirror/releases/$arch/autobuilds/current-stage3-$arch-systemd/$tarball" \
		| tar xpJ
}

log() {
	printf "[%s] %s\n" "$(date -u +%FT%TZ)" "$*"
}

main "$@"
