sudo sh <<"EOF"
meh() { printf " \033[1;32m*\033[0m %s\n" "${*}"; }
omg() { printf " \033[1;33m*\033[0m %s\n" "${*}"; }
wtf() { printf " \033[1;31m* FAIL\033[0m %s\n" "${*}"; exit 1; }

makeopts=-j8
target=amd64
config=GENERIC

home="/usr/home/cyberleo/worlds"

world="${home}/${target}/$(echo "${config}" | tr 'A-Z' 'a-z')"

seed="${home}/seed/src"
build="${home}/seed/root"

date="$(date +%Y%m%d)"

prepare() {
  meh "Preparing build environment"
  [ -d "${build}" ] && wtf "${build}: directory exists"
  mkdir -p "${build}" || wtf
  cat "${seed}"/base.?? | tar xCf "${build}" - || wtf
  mkdir -p "${build}/usr/obj" || wtf

  meh "Mounting chroot directories"
  mkdir -p "${worlds}/root"
  mount -t devfs devfs "${build}/dev" || wtf
  mount -t nullfs /usr/src "${build}/usr/src" || wtf
  mount -t nullfs /usr/obj "${build}/usr/obj" || wtf
  mount -t nullfs "${world}/root" "${build}/mnt" || wtf
}

cleanup() {
  meh "Cleaning up"
  umount -f "${build}/mnt"
  umount -f "${build}/usr/obj"
  umount -f "${build}/usr/src"
  umount -f "${build}/dev"
  mount | grep -q "${build}" && wtf "Stuff is still mounted under ${build}; not removing"
  chflags -R noschg "${build}"
  rm -Rf "${build}"
}
trap "cleanup" exit hup int term kill

mount | grep -q "${build}" && wtf "Stuff is mounted under ${build}"

if [ -d "${build}" ]
then
  omg "${build}: directory exists; purging"
  cleanup
fi

prepare

meh "==> Building in seed ${seed} for ${target}-${config} in ${build}; destdir is ${worlds}"

for phase in buildworld buildkernel distrib-dirs installworld installkernel distribution
do
  meh "==> Phase: ${phase}"
  script "${world}/${date}-${phase}.log" chroot "${build}" sh -c \
    "cd /usr/src; time make ${makeopts} ${phase} TARGET=${target} KERNCONF=${config} DESTDIR=/mnt" || wtf
done
EOF