#!/bin/sh
#
# Script run on the clients, to set them up in preparation for building
# packages.  This includes setting up parts of the /var/portbuild
# directory hierarchy, the portbuild script and the bindist.tar file
# for populating the build chroots.

nocopy=0
if [ "x$1" = "x-nocopy" ]; then
  nocopy=1
  shift
fi

if [ $# != 6 ]; then
  echo "usage: $0 [-nocopy] master portbuilddir branch tmpdir md5"
  exit 1
fi

master=$1
pb=$2
arch=$3
branch=$4
tmpdir=$5
md5master=$6

if [ $(echo $(/sbin/mount | grep "${pb}/.*read-only" | awk '{print $3}' | wc -c)) != 0 ]; then
  /sbin/umount -f $(/sbin/mount | grep "${pb}/.*read-only" | awk '{print $3}')
fi

#cd ${pb}
#fs=$(df . | sed -e '1d' | awk '{print $6}')

#mount -u -w $fs

cd ${tmpdir}

mkdir -p ${tmpdir}/${branch}/chroot

# Clean up the tmpdir
# XXX Should try and unmount old nfs filesystems first 
if ! rm -rf ${tmpdir}/${branch}/chroot/* >/dev/null 2>&1; then
  chflags -R noschg ${tmpdir}/${branch}/chroot/*
  rm -rf ${tmpdir}/${branch}/chroot/*
fi

killall make fetch >/dev/null 2>&1

mkdir -p ${tmpdir}/${branch}/tarballs
if [ "$nocopy" = 0 ]; then
  if [ -f ${tmpdir}/${branch}/tarballs/bindist.tar ]; then
    md5=$(/sbin/md5 ${tmpdir}/${branch}/tarballs/bindist.tar | awk '{print $4}')
  fi
  if [ "${md5}" = "${md5master}" ]; then
    echo "not copying bindist to $(hostname -s) since it is already up to date"
  else
    echo "copying bindist to $(hostname -s)"
    cp -p ${pb}/${arch}/${branch}/tarballs/bindist.tar ${tmpdir}/${branch}/tarballs
  fi
fi

#mount -u -r $fs
