#!/bin/bash

# get the lock - USE THE SAME LOCK AS THE MIRROR TO AVOID OVERLAPS
# - don't retry too hard, it's ok if we miss a run
# - single-server so -p means we'll consider the lock stale
#   if the pid isn't around
# 
echo "Acquiring lock..."
dotlockfile -p -r2 /var/tmp/moodle-sync.lock || exit 1

TMPDIR="`mktemp -d`"

export PATH=~/bin:$PATH;

function finalize {
  echo "Releasing lock..."
  dotlockfile -u  /var/tmp/moodle-sync.lock || echo "could not release lock"
  rm -rf $TMPDIR
}

function error {
  echo "git error encountered, exiting..."
  finalize
  exit 1
}

echo 1>&2 MOODLE-R2

echo "Running cvsps"
TZ=UTC cvsps --norc -x --cvs-direct -u -A --root /git/import/moodle/moodlemirror.cvs moodle 1> $TMPDIR/moodle-utc.cvsps 2> /dev/null || error

echo "Running git-cvsimport"
GIT_DIR=/git/import/moodle/moodle-import-r2.git git-cvsimport -i -P $TMPDIR/moodle-utc.cvsps -v -o cvshead -k -d /git/import/moodle/moodlemirror.cvs moodle 2>&1 | egrep -v '^skip patchset ' | grep -v "Skipping #CVSPS_NO_BRANCH"

echo "Sanity checks"
GIT_DIR=/git/import/moodle/moodle-import-r2.git git-gc || error
GIT_DIR=/git/import/moodle/moodle-import-r2.git git-repack || error
GIT_DIR=/git/import/moodle/moodle-import-r2.git git-fsck --strict || error

echo "Pushing"
GIT_DIR=/git/import/moodle/moodle-import-r2.git   git push --all /git/public/moodle-r2.git || error
GIT_DIR=/git/import/moodle/moodle-import-r2.git git push /git/moodle-upstream/moodle.git MOODLE_16_STABLE || error
GIT_DIR=/git/import/moodle/moodle-import-r2.git git push /git/moodle-upstream/moodle.git MOODLE_17_STABLE || error
GIT_DIR=/git/import/moodle/moodle-import-r2.git git push /git/moodle-upstream/moodle.git MOODLE_18_STABLE || error
GIT_DIR=/git/import/moodle/moodle-import-r2.git git push /git/moodle-upstream/moodle.git MOODLE_19_STABLE || error
GIT_DIR=/git/import/moodle/moodle-import-r2.git git push /git/moodle-upstream/moodle.git cvshead || error


echo 1>&2 MOODLE-LANG

echo "Running git-cvsimport"
GIT_DIR=/git/import/moodle/moodle-lang-import.git git cvsimport -i -p ' -x ' -o cvshead -k -d /git/import/moodle/moodlemirror.cvs lang || error

echo "Sanity checks"
GIT_DIR=/git/import/moodle/moodle-lang-import.git git-gc || error
GIT_DIR=/git/import/moodle/moodle-lang-import.git git-repack || error
GIT_DIR=/git/import/moodle/moodle-lang-import.git git-fsck --strict || error

echo "Pushing"
GIT_DIR=/git/import/moodle/moodle-lang-import.git git push --all /git/public/moodle-lang.git || error

# release me!
finalize

