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

pb=/var/portbuild
. ${pb}/conf/server.conf

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

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 8; do
for branch in $SRC_BRANCHES; do
  cd ${base}${branch}
  fulldate=$(date)
  supdate=$(supstamp ${fulldate})
  eval tag=\$SRC_BRANCH_${branch}_TAG
  cat ${SRC_MASTER_SUPFILE} | \
    sed "s|%%DATE%%|${supdate}|;s|%%PREFIX%%|${base}${branch}|;s|%%TAG%%|${tag}|" \
    > ${SRC_SUPFILE}.${branch}.now
  # example destination directory: /a/snap/src-6/src/ (tricky!)
  csup -L 2 ${SRC_SUPFILE}.${branch}.now > src-csup.${branch}.log
  echo ${fulldate} > src/.updated
  # hack for zfs breakiness
  find . -group wheel|xargs chgrp portmgr
  snapdate=$(stamp ${fulldate})
  zfs snapshot ${zbase}${branch}/src@${snapdate}
done

finish 0
