#!/bin/bash
# Set a property in the top-level catalog 
# Run this on the repository server

ME="`basename $0`"

usage()
{
    echo "Usage: $ME property_name property_value [reponame]" >&2
    echo "example: $ME TTL 900 oasis.opensciencegrid.org" >&2
    exit 1
}

if [ $# = 3 ]; then
    REPO="$3"
elif [ $# = 2 ]; then
    REPLICAS="`ls /srv/cvmfs/*/.cvmfs_master_replica 2>/dev/null`"
    if [ -z "$REPLICAS" ]; then
	REPLICAS="`ls /srv/cvmfs/*/pub/catalogs/.cvmfs_master_replica 2>/dev/null`"
    fi
    if [ -z "$REPLICAS" ]; then
	echo "$ME: No master repositories found" >&2
	usage
    fi
    if [ `echo "$REPLICAS"|wc -l` != 1 ]; then
	echo "$ME: More than one repository found, specify one" >&2
	usage
    fi
    REPO="`echo "$REPLICAS"|cut -d/ -f4`"
else
    usage
fi

KEY="$1"
VALUE="$2"

insert_or_update()
{
    OLDVAL="`sqlite3 $1 "SELECT value FROM properties WHERE key='$2'"`"
    if [ -z "$OLDVAL" ]; then
	sqlite3 $1 "INSERT INTO properties VALUES('$2', '$3')"
    else
	sqlite3 $1 "UPDATE properties SET value='$3' WHERE key='$2'"
    fi
    echo "New value for $2: `sqlite3 $1 "SELECT value FROM properties WHERE key='$2'"`"
}

set -e

if [ -f /srv/cvmfs/$REPO/pub/catalogs/.cvmfs_master_replica ]; then
    # cvmfs 2.0.x
    insert_or_update /srv/cvmfs/$REPO/pub/catalogs/.cvmfscatalog.working "$KEY" "$VALUE"
    cvmfs_server publish
elif [ -f /srv/cvmfs/$REPO/.cvmfs_master_replica ]; then
    # cvmfs 2.1.x
    TMPFILE="`mktemp /tmp/setrepoprop.XXXXXXXXXX`"
    trap "rm -f ${TMPFILE}*" 0
    cvmfs_server transaction $REPO
    mknod $TMPFILE.in p
    mknod $TMPFILE.out p
    (
    # script is used to prevent output buffering
    script -f -q -c "cvmfs_server publish -p $REPO <$TMPFILE.in" $TMPFILE.out >/dev/null 2>&1 &
    while read P1 P2 P3 P4 P5 REST; do
	if [ "$P1 $P2 $P3 $P4" = "Allowing for tweaks in" ]; then
	    insert_or_update $P5 "$KEY" "$VALUE"
	    # send a blank line to the input of cvmfs_server publish
	    echo >&3
	else
	    echo "$P1 $P2 $P3 $P4 $P5 $REST"
	fi
    done <$TMPFILE.out
    ) 3>&1 >&2 | head -1 | tee $TMPFILE.in >/dev/null
else 
    echo "$ME: cannot locate the catalog of $REPO" >&2
    exit 1
fi


