#!/bin/sh

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

# This script cannot output anything except the name of the successfully
# claimed chroot.  In case of error, just exit.

# XXX Return the string "chroot=*" and look for that in pdispatch to make
# this more robust

# configurable variables
pb=/var/portbuild

arch=$1
shift

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

buildroot=${scratchdir}

branch=$1
shift

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

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

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

# Perform initial sanity check

if [ ! -z "${squid_dir}" ]; then
  /usr/local/sbin/squid -k check 2> /dev/null
  status=$?
  if [ "${status}" != "0" ]; then
    touch ${scratchdir}/.squid
    /usr/local/etc/rc.d/squid.sh start > /dev/null &
    exit 1
  else
    rm -f ${scratchdir}/.squid
  fi
fi

# Check for enough disk space
df=$(df -k ${scratchdir} | tail -1 | awk '{print $4}')

if [ ${df} -lt 102400 ]; then
  touch ${scratchdir}/.disk
  exit 1
else
  rm -f ${scratchdir}/.disk
fi

found=0
# Look for pre-existing chroot directories that are populated and unused
for dir in ${chrootdir}/*; do
  if [ -f ${dir}/.ready -o -f ${dir}/.dirty ]; then
    # Atomically claim the directory
    mkdir ${dir}/used 2>/dev/null || continue
    touch ${dir}/used/${pkgname}
    if [ -f ${dir}/.dirty ]; then
      ${pb}/scripts/clean-chroot ${arch} ${branch} ${dir} 2 &
      continue
    fi
    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
  if [ "${use_md_swap}" = "1" ]; then
    unit=$(mdconfig -a -t swap -s ${md_size})
    newfs /dev/${unit} > /dev/null
    chrootnum=$(echo ${unit} | sed 's,md,,')
    chroot=${chrootdir}/${chrootnum}
    mkdir -p ${chroot}/used 2>/dev/null || continue
    # Need to make sure that used/ is also present after mounting the fresh md so as to not leave open any races
    mount -o async /dev/${unit} ${chroot}/used
    mkdir ${chroot}/used/used
    touch ${chroot}/used/used/${pkgname}
    umount ${chroot}/used
    mount -o async /dev/${unit} ${chroot}/
  else
    chrootnum=$(($chrootnum+1))
    chroot=${chrootdir}/${chrootnum}
    mkdir -p ${chroot} 2>/dev/null || continue
    mkdir ${chroot}/used 2>/dev/null || continue
  fi
  touch ${chroot}/used/${pkgname}
  touch ${chroot}/.notready
  found=1
done

echo ${chroot}
