#!/bin/ksh -x
# This script will update (or create) a new machine tree for CONGEN.
# Usage: update_tree machine_name

usage()
{
echo "Usage: update_tree machine_name" ;
}

dotify()
{
# Convert all directories in the argument to ..

newname=
arg=$1
typeset -i count=0
while [[ $arg != . ]] do
  newname=${newname}../
  arg=`dirname $arg`
  if (( (count+=1) > 200 )) ; then
    echo "Infinite loop broken" 1>&2
    exit 1
  fi
done
}

################## Start of script #####################

# Check arguments

if [[ $# -ne 1 ]] ; then
  usage
  exit 1
fi

curdir=`pwd`
cd $CGROOT

if [[ ! -r master_machine ]] ; then
  echo "Unable to read master machine name in `pwd`/master_machine."
  exit 1
fi

master=`cat master_machine`

if [[ $1 = $master ]] ; then
  echo "It is not permitted to update the master directory tree for"
  echo "CONGEN with this command."
  exit 1
fi

# Get the new directory ready

cd $CGROOT/$master/
olddir=`pwd`
newdir=$CGROOT/$1/

if [[ ! -w $newdir ]] ; then
  mkdir -p $newdir
fi

if [[ ! -d $newdir ]] ; then
  echo "$newdir is not a directory!"
  exit 1
fi

cd $newdir
newdir=`pwd`

# Move the files

rdist -ochksym,ignlnks,remove -d OLDDIR=$olddir -d NEWDIR=$newdir -f - <<'RDIST_EOF'
${OLDDIR} -> localhost
    install ${NEWDIR};
    except_pat (/RCS/ /bin/ /lib/ /test/archive/ 
		\\.o\$ \\.fli\$ \\.fi\$ \\.f\$ \\.a\$ \\.out\$ test/.*\\.cg
		\\.dif\$ /foo core\$ \\.BAK\$ \\.CKP\$ ~\$ \#\$
		\\.tar\$ \\.tar.Z\$ \\.shar\$ ) ;
RDIST_EOF

rdist -ochksym,ignlnks,remove -d OLDDIR=$olddir -d NEWDIR=$newdir -f - <<'RDIST_EOF'
${OLDDIR}/v2/support/src/flecs -> localhost
    install ${NEWDIR}/v2/support/src/flecs;
    except_pat (/RCS/ 
		\\.out\$ 
		\\.dif\$ /foo core\$ \\.BAK\$ \\.CKP\$ ~\$ \#\$
		\\.tar\$ \\.tar.Z\$ \\.shar\$ ) ;
RDIST_EOF

rdist -ochksym,ignlnks,remove -d OLDDIR=$olddir -d NEWDIR=$newdir -f - <<'RDIST_EOF'
${OLDDIR}/v2/support/src/porttest -> localhost
    install ${NEWDIR}/v2/support/src/porttest;
    except_pat (/RCS/ 
		\\.out\$ 
		\\.dif\$ /foo core\$ \\.BAK\$ \\.CKP\$ ~\$ \#\$
		\\.tar\$ \\.tar.Z\$ \\.shar\$ ) ;
RDIST_EOF

rdist -ochksym,ignlnks,remove -d OLDDIR=$olddir -d NEWDIR=$newdir -f - <<'RDIST_EOF'
${OLDDIR}/v2/bin/install -> localhost
    install ${NEWDIR}/v2/bin/install;
RDIST_EOF

# Point all the RCS directories back to the master machine except
# for the test archive.

cd $newdir

rcsdirs=`find . -name RCS -print`

for dir in $rcsdirs ; do
  if [[ $dir != */test/archive/* ]] ; then
    dotify $dir
    newname=${newname#../}
    dir=${dir#./}
    headdir=`dirname $dir`
    basedir=`basename $dir`
    rm -rf $dir
    (cd $headdir; ln -s ${newname}../$master/$dir $basedir)
  fi
done

cd $newdir/v2/test
if [[ -r archive/RCS/cgpara1_ref.cmp,v ]]
then
  rm -f cgpara1_ref.cmp 
fi
if [[ -r archive/RCS/cgpbe2_ref.cmp,v ]]
then
  rm -f cgpbe2_ref.cmp 
fi

