#!/bin/sh 
# BLURB gpl
# 
#                            Coda File System
#                               Release 5
# 
#           Copyright (c) 1987-1999 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
# 
#*/

if [ `cat /vice/hostname` != `cat /vice/db/scm` ]
then
        echo "This must be run from the scm ("`cat /vice/db/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

# Look up the replicated volume name in /vice/db/VRList to determine the
# VolIDs of the replicated copies.
REPVOLNAME=$1
REPS=`awk '$1 ~ /^'$REPVOLNAME'$/ {for (i=4; i< $3 + 4; i++) printf "%s ", $i}' /vice/db/VRList`


# Check to see if the volume actually exists 
if [ -z "$REPS" ]
then
	echo "Volume" $REPVOLNAME "doesn't exist!"
	exit 1
fi

REPVOLID=`awk '$1 ~ /^'$REPVOLNAME'$/ {print $2}' /vice/db/VRList`
VSG=`awk '$1 ~ /^'$REPVOLNAME'$/ {print $12}' /vice/db/VRList`
HOSTS=`grep -i "^$VSG" /vice/db/VSGDB | sed "s/$VSG//"`


# Remove the individual copies
for host in $HOSTS
do
  volumelist=`volutil -h $host getvolumelist 2>/dev/null`

  for repid in $REPS 
  do
    volumes=`echo "$volumelist" | awk '$8 ~/^W'$repid'$/ { 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 $host"
        volutil -h "$host" purge "$volid" "$volname" 2>/dev/null
      else
        echo "Would have purged $volname ($volid) from $host"
      fi
    done
  done
done

if [ $dryrun = 0 ] ; then
  # Delete the entry for the volume from the VRList
  awk ' $1 !~ /^'$REPVOLNAME'$/ { print } ' /vice/db/VRList >/vice/db/VRList.tmp
  mv /vice/db/VRList.tmp /vice/db/VRList

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

  # Make sure that the vldb and vrdb are updated.
  volutil makevrdb /vice/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

