#! /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
# 
#*/

echon() {
    if [ "`echo -n`" ] ; then
        echo "$@"\c
    else
        echo -n "$@"
    fi
}

PATH=$PATH:/usr/sbin
export PATH

# load the server configuration file
vicedir=/vice
. "`codaconfedit server.conf`"

if [ ! -f ${vicedir}/hostname -o ! -f ${vicedir}/db/scm ] ; then
   echo "Coda server configuration error.  Could not find needed files."
   exit 1
fi

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

# Parse arguments
if  [ $# -lt 2 -o $# -gt 4 ]; then
	echo "bad args:  createvol_rep <volname> <vsgaddr> [<partition-name>] [<groupid>]"
	exit
fi

# Initialize local variables
SERVERS=
NSERVERS=0
MAXSERVERS=8

# deal with Parameters 
VOLNAME=$1
VSGADDR=$2
PARTITION=$3

#
# Create these files if they don't already exist.

# VRList was moved from vice/vol to vice/db in Coda 5.3.11
if [ ! -f "${vicedir}/db/VRList" -a -f "${vicedir}/vol/VRList" ] ; then
  echo "Moving ${vicedir}/vol/VRList to ${vicedir}/db"
  cp "${vicedir}/vol/VRList" "${vicedir}/db/VRList" && rm ${vicedir}/vol/VRList
  # Need to replicate VRList and maxgroupid too
  echo VRList >> "${vicedir}/db/files"
  echo maxgroupid >> "${vicedir}/db/files"
fi
touch "${vicedir}/db/VRList"

if [ ! -f "${vicedir}/vol/BigVolumeList" ] ; then
    echo "Getting initial version of ${vicedir}/vol/BigVolumeList."
    volutil -h `cat ${vicedir}/db/scm` getvolumelist ${vicedir}/vol/BigVolumeList
fi

# Validate the <volname> parameter
if  [ x$VOLNAME = "x`awk ' $1 ~ /^[WRB]'$1'$/  {print $1}' ${vicedir}/vol/BigVolumeList`" ]; then
    echo "$VOLNAME exists as a non replicated volume in ${vicedir}/vol/BigVolumeList"
    exit 1
fi

if [ x$VOLNAME = x`awk ' $1 ~ /^[WRB]'$1'\.[0-7]$/  {print $1}' ${vicedir}/vol/BigVolumeList` ]; then
    echo "$VOLNAME exists as a replica in ${vicedir}/vol/BigVolumeList"
    exit 1
fi

# Dump the VRDB from RVM into a temporary VRList list
rm -f "${vicedir}/db/VRList.new"
volutil -h `cat ${vicedir}/db/scm` dumpvrdb "${vicedir}/db/VRList.new"
if [ $? -ne 0 ]; then
    echo "Failed to dump the current VRDB into ${vicedir}/db/VRList.new"
    exit 1
fi

if [ x$VOLNAME = "x`awk ' $1 ~ /^'$1'$/  {print $1}' ${vicedir}/db/VRList.new`" ]; then
	echo "Volume $VOLNAME already exists in ${vicedir}/db/VRList"
	exit 1
fi

# Derive the server list from the <vsgaddr> parameter
SERVERS=`awk '$1 ~ /^'$VSGADDR'$/ {print $2, $3, $4, $5, $6, $7, $8, $9}' ${vicedir}/db/VSGDB`
echo Servers are \($SERVERS\)
NSERVERS=`echo $SERVERS | wc -w` 


# Validate the server list
if [ $NSERVERS -eq 0 -o  $NSERVERS -gt $MAXSERVERS ]; then
	echo Specify 1 - $MAXSERVERS servers
	exit 1
fi 


for SERVER in $SERVERS ; do
	grep $SERVER ${vicedir}/db/servers > /dev/null 
	if [ $? -ne 0 ];  then
		echo Server $SERVER not in servers file
		exit 1
	fi
done

# Check the partitions or find them if not specified.
PART=""
for SERVER in $SERVERS ; do
        grep "^P"  ${vicedir}/vol/BigVolumeList | \
	      awk "/ H$SERVER[\. ]/ "'{print $1}' | \
	      sed -e "s/^P//g" > /tmp/cvr.$$  
	np=`cat /tmp/cvr.$$ | wc -w`
	if [ $np -eq 0 ]; then
	    volutil -h $SERVER getvolumelist /tmp/vollist.$$
	    cat /tmp/vollist.$$ >> ${vicedir}/vol/BigVolumeList
	    rm -f /tmp/vollist.$$
	    grep "^P"  ${vicedir}/vol/BigVolumeList | \
	        awk "/ H$SERVER[\. ]/ "'{print $1}' | \
	        sed -e "s/^P//g" > /tmp/cvr.$$  
	    np=`cat /tmp/cvr.$$ | wc -w`
	    if [ $np -eq 0 ]; then
		echo Found no partitions for server $SERVER.
		exit 1
	    fi
	fi 
        if [ $# -eq 2 ]; then
	    if [ $np -gt 1 ]; then
		echo Found 2 or more partitions for server $SERVER.   You
		echo must specify a partition.
		exit 1
	    fi
	    PART="$PART"`cat /tmp/cvr.$$`" "
	else
	    if ! grep "^$PARTITION\$" /tmp/cvr.$$ > /dev/null ; then
		volutil -h $SERVER getvolumelist /tmp/vollist.$$
		cat /tmp/vollist.$$ >> ${vicedir}/vol/BigVolumeList
		rm -f /tmp/vollist.$$
		grep "^P"  ${vicedir}/vol/BigVolumeList | \
		    awk "/ H$SERVER[\. ]/ "'{print $1}' | \
		    sed -e "s/^P//g" > /tmp/cvr.$$  
		if ! grep "^$PARTITION\$" /tmp/cvr.$$ > /dev/null ; then
		    echo Partition $PARTITION not found on server $SERVER.
		    exit 1;
		fi
	    fi
	fi
done
rm -f /tmp/cvr.$$

# Allocate a new groupid if necessary
if  [ $# -le 3 ]; then
# New location for maxgroupid -- move it.
        if  [ -f ${vicedir}/vol/maxgroupid ]; then
		mv ${vicedir}/vol/maxgroupid ${vicedir}/db/maxgroupid
	fi
	if  [ -f ${vicedir}/db/maxgroupid ]; then
		GROUPID=`cat ${vicedir}/db/maxgroupid`
		HEXGROUPID=`printf %x $GROUPID`
		MAXGROUPID=`expr $GROUPID + 1`
		echo $MAXGROUPID > ${vicedir}/db/maxgroupid
	else
		echo ${vicedir}/db/maxgroupid not found
		exit 1
	fi
else
	HEXGROUPID=$4
fi

echo HexGroupId is $HEXGROUPID


# Create the new volumes
N=0
ENTRY="$VOLNAME $HEXGROUPID $NSERVERS"
for  SERVER in $SERVERS ; do
	if [ $# -eq 2 ]; then
	    PARTITION=${PART%% *}
	    PART=${PART#* }
 	fi
	echo "creating volume $VOLNAME.$N on $SERVER (partition $PARTITION)" 
	volutil -h $SERVER create_rep $PARTITION $VOLNAME.$N $HEXGROUPID > /tmp/out
	if [ $? -ne 0 ]; then 
		echo "Failure to make volume on $SERVER!. Abort.".
		exit 1
	fi

	# grab the volume number.
	volnum=`cut -d' ' -f2 /tmp/out`
	ENTRY="$ENTRY $volnum"
	rm -f /tmp/out

	N=`expr $N + 1`
done

# HACK, disable resolution on singly replicated volumes. The server should
# really be doing this.
if [ $N -eq 1 ] ; then
    volutil -h $SERVERS setlogparms $volnum reson 0
fi

# Rebuild the VLDB
bldvldb.sh $SERVERS

# Update the VRList and rebuild the VRDB
# We already got the replica id's.
# add nulentries and VSGDB to entry
while true  ; do
        if [ $N -eq 8 ]; then
	    break
	fi
        ENTRY="$ENTRY 0"
	N=`expr $N + 1`
done

ENTRY="$ENTRY $VSGADDR"

echo "<echo $ENTRY >> ${vicedir}/db/VRList.new>"
echo $ENTRY >> ${vicedir}/db/VRList.new
volutil makevrdb ${vicedir}/db/VRList.new

if [ $? -ne 0 ]; then
    echo "Failed to create a new VRDB file from ${vicedir}/db/VRList.new"
    exit 1
fi

# All seemed to have gone well. Make a backup of the old VRList and move the
# new VRList in it's place.
mv ${vicedir}/db/VRList ${vicedir}/db/VRList.old
mv ${vicedir}/db/VRList.new ${vicedir}/db/VRList

echon "Do you wish this volume to be Backed Up (y/n)? [n] "

read _ans_

if  [ x$_ans_ = xy -o x$_ans_ = xyes ]; then
    echon "Day to take full dumps: [Mon] "

    read day

    if [ x"$day" = x"" ]; then 
	day="Mon"	
    fi

    case $day in 
       [Ss][Uu][Nn]*)
	    _cycle_="FIIIIII" ;;
	[Mm][Oo][Nn]*)
	    _cycle_="IFIIIII" ;;
	[Tt][Uu][Ee]*)
	    _cycle_="IIFIIII" ;;
	[Ww][Ee][Dd]*)
	    _cycle_="IIIFIII" ;;
	[Tt][Hh][Uu]*)
	    _cycle_="IIIIFII" ;;
	[Ff][Rr][Ii]*)
	    _cycle_="IIIIIFI" ;;
	[Ss][Aa][Tt]*)
	    _cycle_="IIIIIIF" ;;
	*) 
            echo "$day" is not a valid day, not adding $VOLNAME to backup list.
	    exit 
	    ;;
    esac

    echo "echoing $HEXGROUPID        $_cycle_        $VOLNAME >>${vicedir}/db/dumplist"
    echo "$HEXGROUPID        $_cycle_         $VOLNAME" >>${vicedir}/db/dumplist

    # Generate a disklist for Amanda while we're at it
    #for SERVER in $SERVERS ; do
    #	echo $SERVER $VOLNAME coda >> ${vicedir}/db/disklist.amanda
    #done
fi

