#!/bin/sh 
# BLURB gpl
# 
#                            Coda File System
#                               Release 6
# 
#           Copyright (c) 1987-2003 Carnegie Mellon University
#                   Additional copyrights listed below
# 
# This  code  is  distributed "AS IS" without warranty of any kind under
# the terms of the GNU General Public Licence Version 2, as shown in the
# file  LICENSE.  The  technical and financial  contributors to Coda are
# listed in the file CREDITS.
# 
#                         Additional copyrights
#                            none currently
# 
#*/

prefix=/usr/pkg
exec_prefix=${prefix}

PATH=$PATH:${prefix}/sbin
export PATH

# load the server configuration file
vicedir=/vice
. "`${exec_prefix}/sbin/codaconfedit server.conf`"

SCM=`cat ${vicedir}/db/scm`
if [ `cat ${vicedir}/hostname` != "${SCM}" ]
then
        echo "This must be run from the scm (${SCM})"
        exit 1
fi

# Check that the input parameters are correct
if [ $# = 0 -o "$1" = "-h" -o "$1" = "--help" ]
then
	echo "purgevol_rep volumename"
	exit 1
fi

if [ "$1" = "--kill" ]
then
    dryrun=0
    shift
else
    dryrun=1
    echo "Only testing, use 'purgevol_rep --kill $1' to really purge the volume"
fi

# Ask the SCM where the volume is located.
REPVOLNAME=$1
volinfo=`${exec_prefix}/bin/getvolinfo ${SCM} ${REPVOLNAME}`
if [ $? -ne 0 ]
then
    echo "Couldn't get volume location information for ${REPVOLNAME}"
    exit 1
fi

NSERVERS=`echo $volinfo | sed 's/.* ServerCount \([^ ]*\) .*/\1/'`

N=0
while [ $N -ne $NSERVERS ]
do
  REP=`echo $volinfo | sed 's/.* Replica'$N' id \([^,]*\),.*/\1/'`
  SRV=`echo $volinfo | sed 's/.* Server'$N' \([^ ]*\) .*/\1/'`
    
  volumelist=`volutil -h $SRV getvolumelist 2>/dev/null`
  volumes=`echo "$volumelist" | awk '$8 ~/^W'${REP}'$/ { print $2 }'`

  for vid in $volumes
  do
    volid=`echo $vid | cut -c2-`
    volname=`echo "$volumelist" | grep "I$volid" | cut -d' ' -f1 | cut -c2-`

    if [ $dryrun = 0 ] ; then
      echo "Purging $volname ($volid) from $SRV"
      volutil -h "$SRV" purge "$volid" "$volname" 2>/dev/null
    else
      echo "Would have purged $volname ($volid) from $SRV"
    fi
  done
  HOSTS="$HOSTS $SRV"
  N=`expr $N + 1`
done

if [ $dryrun = 0 ] ; then
  REPVOLID=`grep $REPVOLNAME ${vicedir}/db/VRList | cut -d ' ' -f2`

  # Delete the entry from the backup list.
  awk ' $1 !~ /^'$REPVOLID'$/ { print } ' ${vicedir}/db/dumplist >${vicedir}/db/dumplist.tmp
  mv ${vicedir}/db/dumplist.tmp ${vicedir}/db/dumplist

  # Delete the entry for the volume from the VRList
  awk ' $1 !~ /^'$REPVOLNAME'$/ { print } ' ${vicedir}/db/VRList >${vicedir}/db/VRList.tmp
  mv ${vicedir}/db/VRList.tmp ${vicedir}/db/VRList

  # Make sure that the vldb and vrdb are updated.
  volutil -h "${SCM}" makevrdb ${vicedir}/db/VRList
  bldvldb.sh $HOSTS 
else
  echo "Don't forget we were only testing"
  echo "use 'purgevol_rep --kill $1' to really purge the volume"
fi

