#!/bin/sh

# usage: claim-chroot ${arch} ${branch} ${pkgname}

# configurable variables
pb=/var/portbuild

arch=$1
shift

. ${pb}/${arch}/portbuild.conf
. ${pb}/${arch}/portbuild.$(hostname)
. ${pb}/scripts/buildenv

buildroot=${scratchdir}
error=0

branch=$1
shift

buildenv ${pb} ${arch} ${branch}

pkgname=$(basename $1 ${PKGSUFFIX})

chrootdir=${buildroot}/${branch}/chroot

found=0
# Look for pre-existing chroot directories that are populated and unused
for dir in ${chrootdir}/*; do
  if [ -f ${dir}/.ready -a -d ${dir}/tmp ]; then
    # Atomically claim the directory
    mkdir ${dir}/used 2>/dev/null || continue
    touch ${dir}/used/${pkgname}
    found=1
    chroot=${dir}
    break
  fi
done

chrootnum=$$
# If we didn't find a pre-existing directory, create and claim a new one.
while [ ${found} != 1 ]; do
  chrootnum=$((chrootnum+1))
  chroot=${chrootdir}/${chrootnum}
  mkdir -p ${chroot} 2>/dev/null || continue
  mkdir ${chroot}/used 2>/dev/null || continue
  touch ${chroot}/used/${pkgname}
  touch ${chroot}/.notready
  found=1
done

echo ${chroot}
