#!/bin/sh
#
# Update the master source trees that are used by package builds
# and other consumers

pbc=${PORTBUILD_CHECKOUT:-/var/portbuild}

. ${pbc}/conf/server.conf

base=${ZFS_MOUNTPOINT}/${SNAP_SRC_DIRECTORY_PREFIX}
zbase=${ZFS_VOLUME}/${SNAP_SRC_DIRECTORY_PREFIX}

VERBOSE=1

supstamp() {
	fulldate=$1
        date -j -f %+ "${fulldate}" +%Y.%m.%d.%H.%M.%S
}

stamp() {
	fulldate=$1
        date -j -f %+ "${fulldate}" +%Y%m%d%H%M%S
}

finish() {
    err=$1

    end=$(date +%s)
    echo "Finished at $(date)"
    len=$((end-begin))
    echo "Duration = $(date -j -f %s +%H:%M:%S ${len})"
    exit 1
}

begin=$(date +%s)
echo "Started at $(date)"

# We need to preserve group writability so portmgr group can write
umask 002

for branch in $SRC_BRANCHES; do
  mountpoint=${base}${branch}
  if [ ! -d ${mountpoint}/src ]; then
    echo "creating new source branch under ${mountpoint}"
    mkdir -p ${mountpoint}
    echo "zfs create -o mountpoint=${mountpoint} ${zbase}${branch}"
    zfs create -o mountpoint=${mountpoint} ${zbase}${branch}
    mkdir -p ${mountpoint}/src
    echo "zfs create -o mountpoint=${mountpoint}/src ${zbase}${branch}/src"
    zfs create -o mountpoint=${mountpoint}/src ${zbase}${branch}/src
    chown -R portmgr:portmgr ${mountpoint}
    chmod -R g+w ${mountpoint}
  fi
  cd ${mountpoint}
  fulldate=$(date)
  supdate=$(supstamp ${fulldate})
  eval tag=\$SRC_BRANCH_${branch}_TAG
  # example destination directory: /a/snap/src-7/src/ (tricky!)
  if [ $VERBOSE ]; then
    echo "svn up"
  fi
  svn up
  echo ${fulldate} > src/.updated
  # hack for zfs breakiness
  find . -group wheel|xargs chgrp portmgr
  snapdate=$(stamp ${fulldate})
  if [ $VERBOSE ]; then
    echo "zfs snapshot ${zbase}${branch}/src@${snapdate}"
  fi
  zfs snapshot ${zbase}${branch}/src@${snapdate}
done

finish 0
