#!/bin/bash
#
# CERNVM Synchronization System - cvmfs-update-client
# Initiator of the synchronization procedure. It connects to the specified
# repository to ask for automatic retrieval.
#
# svn:/cvmfs-update/trunk/cvmfs-update-client
#
# January 2010 Changes by Jakob Blomer <jblomer@cern.ch>
# 2009-02-18 Carlos Aguado Sanchez <caguado@cern.ch>
# Original idea by Steffen Klemer <moh@gmx.org>
#

[ -f /etc/cernvm/cvmfs.conf ] && . /etc/cernvm/cvmfs.conf
[ -f /etc/cvmfs/server.conf ] && . /etc/cvmfs/server.conf
[ -f /etc/cvmfs/server.local ] && . /etc/cvmfs/server.local

for reqvar in CVMFS_UPDATE_TARGET PUB_DIR CVMFS_REPOSITORY_NAME
do
   eval value=\$$reqvar
   if [ -z "$value" ]; then
      echo "Set a value for $reqvar in /etc/cvmfs/server.local"
      exit 1
   fi
done

# Switch to home directory
cd
   
# Launch remote command ignoring common stopper signals
trap "" SIGHUP SIGINT SIGTERM
SYNC=false
if [ x$1 != "x" ]; then
   for arg in "-C" "--create-and-publish"
   do
      if [ $arg == $1 ]; then
         SYNC=true
      fi
   done
else
  SYNC=true
fi
if [ $SYNC == "true" ]; then
  echo "Pre-snapshot repository"
  timestamp=`date "+%Y%m%d%H%M%S"`
  ssh -l cvmfs $CVMFS_UPDATE_TARGET -- -c "Pre-sync-$timestamp"
  
  cvmfs-sync
  if [ "x$SIGN_CATALOG" == "xyes" ]; then
    if [ "x$CVMFS_CERTIFICATE" != "x" ]; then
      CVMFS_CERTIFICATE="-c $CVMFS_CERTIFICATE"
    fi
    if [ "x$CVMFS_KEYFILE" != "x" ]; then
      CVMFS_KEYFILE="-k $CVMFS_KEYFILE"
    fi
    
    if [ "x$CVMFS_BOOKKEEPING" == "x" ]; then
      for c in `find $PUB_DIR/catalogs -name .cvmfscatalog`
      do
        cvmfs_sign $CVMFS_CERTIFICATE $CVMFS_KEYFILE -n $CVMFS_REPOSITORY_NAME $c
      done
    else
      for c in `cat $CVMFS_BOOKKEEPING`
      do
        cvmfs_sign $CVMFS_CERTIFICATE $CVMFS_KEYFILE -n $CVMFS_REPOSITORY_NAME $c
      done
      cat /dev/null > $CVMFS_BOOKKEEPING
    fi
  fi
fi 
ssh -l cvmfs $CVMFS_UPDATE_TARGET -- $@
#if [ $SYNC == "true" ] && [ "x$CVMFS_APACHE_TARGET" != "x" ]; then
#   echo Remounting CVMFS1 compatibility layer...
#   sleep 10
#   ssh -l cvmfs $CVMFS_APACHE_TARGET 
#fi
