#!/usr/bin/env bash
poweroff_cmd="sudo systemctl poweroff"
default_arch=amd64

boot() {
	case "$arch" in
		amd64)
			qemu=qemu-system-x86_64
			_boot $(cpu_opts x86_64)
			;;
		arm64)
			driveopts="id=root,if=none"
			_boot \
				$(cpu_opts aarch64) \
				-device virtio-blk-pci,drive=root \
				-kernel "$wd/$arch/vmlinuz" \
				-initrd "$wd/$arch/initrd.img" \
				-append "root=/dev/vda3"
			;;
		*)
			echo "Unsupported architecture $arch" >&2
			exit 1
			;;
	esac
}

install() {
	port=$1
	shift 1
	guest_ssh -p $port build@localhost sudo env DEBIAN_FRONTEND=noninteractive \
		apt-get update -y
	guest_ssh -p $port build@localhost sudo env DEBIAN_FRONTEND=noninteractive \
		apt-get install -y -q "$@"
}

add_repository() {
	port=$1
	name=$2
	src=$3
	repo=$(echo $src | cut -d' ' -f1)
	distro=$(echo $src | cut -d' ' -f2)
	cmpnt=$(echo $src | cut -d' ' -f3)
	key=$(echo $src | cut -d' ' -f4)
	if [ "$key" != "" ]
	then
		# Import the GPG key into a user trustdb
		guest_ssh -p $port build@localhost sudo \
			gpg \
			--keyserver hkp://keyserver.ubuntu.com:80 \
			--recv-keys $key

		# Export the GPG key to Apt's key directory
		guest_ssh -p $port build@localhost sudo \
			gpg \
			--output /etc/apt/trusted.gpg.d/$key.gpg \
			--export $key
	fi
	printf 'deb %s %s %s\n' "$repo" "$distro" "$cmpnt" \
		| guest_ssh -p $port build@localhost sudo tee -a /etc/apt/sources.list
	printf 'deb-src %s %s %s\n' "$repo" "$distro" "$cmpnt" \
		| guest_ssh -p $port build@localhost sudo tee -a /etc/apt/sources.list
	guest_ssh -p "$port" build@localhost sudo apt-get update
}

sanity_check() {
	echo "Booting..."
	cmd_boot amd64 8022 qemu &
	trap 'cmd_cleanup 8022' EXIT
	_wait_boot 8022
	echo "Testing sudo..."
	guest_ssh -p 8022 build@localhost sudo ls -a
	echo "Testing apt..."
	guest_ssh -p 8022 build@localhost sudo apt-get update
	install 8022 curl
	echo "Testing networking..."
	guest_ssh -p 8022 build@localhost curl https://builds.sr.ht
	echo "Testing git..."
	guest_ssh -p 8022 build@localhost git --version
	echo "Testing mercurial..."
	guest_ssh -p 8022 build@localhost hg --version
	echo "Everything works!"
	guest_ssh -p 8022 build@localhost sudo systemctl poweroff || true
}
