#!/bin/sh

zbase=a/cache
scratch=a/scratch

arch=amd64
branch=HEAD

dataset=world-${arch}-${branch}
zsync ${dataset} || exit 1

latest=$(zfs list -Ht snapshot | grep "^${zbase}/${dataset}@" | tail -1 | awk '{print $1}')

if [ -z "${latest}" ]; then
	echo "Something went wrong!"
	exit 1
fi

id=$$
while true; do
	if [ \! -d ${scratch}/jail-$id ]; then
		break
	fi
	id=$((id+1))
done
	
jail=${scratch}/jail-${id}
zfs clone ${latest} ${jail}
mount -t devfs foo /${jail}/dev

# Figure out jail IP addr
ipbase=$((${id}+2))
ip1=$(($ipbase /(256*256)))
ip2=$((($ipbase - ($ip1*256*256)) /256))
ip3=$((($ipbase - ($ip1*256*256) - ($ip2*256))))

ipaddr=127.${ip1}.${ip2}.${ip3}
ifconfig lo0 alias ${ipaddr}/32
jail /${jail} jail-$id ${ipaddr} /bin/csh
ifconfig lo0 delete ${ipaddr}
umount -f /${jail}/dev
zfs destroy ${jail}
