#!/bin/csh
#########################################################################
#									#
#  pullsync								#
#									#
#  This script synchronizes a specified output directory with the	#
#  the contents of a remote directory.					#
#									#
#  This script uses rsync, which must be installed on both the local	#
#  device and the remote device.					#
#									#
#  K. Brill/HPC		 9/03						#
#  K. Brill/HPC		12/06	Add delete option			#
#  K. Brill/HPC         08/08   Add update only option			#
#  K. Brill/HPC      20091201   Allow an exclude file			#
#########################################################################

if ( $#argv < 4 ) then
    cat << EOF

    This script synchronizes files in a local directory tree with those
    on a remote device using rsync operating under ssh.  Files are pulled
    from the remote device to a directory networked locally.

	Enter the following on the command line:

	1 -- Remote user id
	2 -- Remote device (platform) name or address
	3 -- Remote directory path
	4 -- Complete path to output directory
        5 -- Optional "D" input to delete files not found in remote path
             or
             Optional "U" to update files only (do not write over newer
             files)

    Example:

    pullsync eff2 hww1 "~eff2/wwe3_archive" /export/hpc1/dtb/wwe3_archive

    The user running this script must have write permission in the output
    path.  Remote file permissions and time stamps are preserved.  The
    local user id will own the files.

    This script uses rsync, which must be installed on both the local
    device and the remote device.  The ssh remote login permissions must
    be in place on the remote device.

    Files or directories may be excluded by listing them in this file:

    pullsync_exclude

    This file must be located under the output directory specified by
    input #4.  Add "pullsync_exclude" as an entry in the file.

EOF
    exit
endif

set remuid=$1
set remdev=$2
set rempth="${3}"/
set lclpth=$4
if ( $#argv == 5 ) then
    set i5 = $5
else
    set i5 = no
endif

cd $lclpth
if ( $status != 0 ) then
    echo $lclpth does not exist.
    exit 1
endif

(echo tst > $$.tst) >& /dev/null
if ( $status != 0 ) then
    echo No write permission at $lclpth.
    /bin/rm -f $$.tst
    exit 1
else
    /bin/rm $$.tst
endif

if ( -e pullsync_exclude ) then
    set inexc="--exclude-from=pullsync_exclude"
else
    set inexc=
endif

if ( $i5 == "D" ) then
    echo rsync -tvrp -e ssh --delete $inexc ${remuid}@${remdev}:"${rempth}" .
    rsync -tvrp -e ssh --delete $inexc ${remuid}@${remdev}:"${rempth}" .
else if ( $i5 == "U" ) then
    echo rsync -tvrpu -e ssh $inexc ${remuid}@${remdev}:"${rempth}" .
    rsync -tvrpu -e ssh $inexc ${remuid}@${remdev}:"${rempth}" .
else
    echo rsync -tvrp -e ssh $inexc ${remuid}@${remdev}:"${rempth}" .
    rsync -tvrp -e ssh $inexc ${remuid}@${remdev}:"${rempth}" .
endif
