#!/usr/bin/bash
# Remove a CVMFS repository to a dual-hosted stratum 1.
# This can be run on either host.
# Written by Dave Dykstra 2 September 2014

. /etc/cvmfs/hastratum1.conf

usage()
{
    echo "Usage: remove-repository [-f] [-h] fqrn" >&2
    echo " -f: force removal, don't ask for confirmation" >&2
    echo " -h: remove only on this half of an HA pair" >&2
    echo " -H; like -h, but leave data" >&2
    exit 1
}

DONTFORCE=true
HALFONLY=false
LEAVEDATA=false
while getopts :fhH OPT; do
    case $OPT in
        f) DONTFORCE=false;;
        h) HALFONLY=true;;
        H) HALFONLY=true; LEAVEDATA=true;;
        \?) echo "Invalid option: -$OPTARG" >&2
            usage;;
    esac
done
shift $((OPTIND-1))

if [ $# != 1 ]; then
    usage
fi

if [ "`id -u`" != 0 ]; then
    echo "Not running as root" >&2
    exit 1
fi

REPO="$1"

SHORTREPO=""
case "$REPO" in
    *.cern.ch|*.opensciencegrid.org)
	SHORTREPO="${REPO%%.*}"
	;;
esac

THISHOST="`uname -n`"
case $THISHOST in
    $HOST1) OTHERHOST=$HOST2;;
    $HOST2) OTHERHOST=$HOST1;;
    *) echo "Not running on $HOST1 or $HOST2" >&2; exit 1;;
esac

if [ ! -d "$STORAGE/$REPO" ]; then
    echo "$STORAGE/$REPO does not exist" >&2
    exit 1
fi

if $DONTFORCE; then
    if $HALFONLY; then
        echo -n "Are you sure you want to remove $REPO on this machine? "
    else
        echo -n "Are you sure you want to remove $REPO from both machines? "
    fi
    read ANS
    case $ANS in
	y*|Y*);;
	*) exit 1;;
    esac
fi

set -ex

if ! $HALFONLY && [ -f /etc/krb5.keytab ]; then
    export KRB5CCNAME=FILE:/tmp/krb5cc_root_hastratum1
    PATH=$PATH:/usr/krb5/bin:/usr/kerberos/bin kinit -k host/$THISHOST
fi

if ! $HALFONLY; then ssh $OTHERHOST rm -f $SRV/$REPO; fi
rm -f $SRV/$REPO
if ! $HALFONLY; then ssh $OTHERHOST rm -rf /var/spool/cvmfs/$REPO; fi
rm -rf /var/spool/cvmfs/$REPO
if ! $HALFONLY; then ssh $OTHERHOST rm -rf /etc/cvmfs/repositories.d/$REPO; fi
rm -rf /etc/cvmfs/repositories.d/$REPO
if ! $HALFONLY; then
    if [ -n "$SHORTREPO" ]; then
        ssh $OTHERHOST rm -f $STORAGE/$SHORTREPO
        rm -f $STORAGE/$SHORTREPO
    fi
    ssh $OTHERHOST rm -rf $STORAGE/$REPO
fi
if ! $LEAVEDATA; then
    rm -rf $STORAGE/$REPO
fi
if [ "`echo $STORAGE/info/*`" != "$STORAGE/info/*" ]; then
    # cvmfs-server 2.2.X or later
    cvmfs_server update-info -e
    if ! $HALFONLY; then rsync -a $STORAGE/info $OTHERHOST:$STORAGE; fi
fi
