#!/bin/sh

#enable command tracking
#set -x

#mirror a subset of the PDB FTP archive

echo ""
echo "From the Schrodinger rsync server, mirror"
echo "a subset of the PDB for use with Prime"
echo ""

#basic rsync settings

#location of local rsync
RSYNC="/usr/bin/rsync"

#remote server name
SERVER=prime.schrodinger.com

#port remote server is using
PORT=23

#is rsync available?
if [ ! -x $RSYNC ]; then
    echo "ERROR: $RSYNC not found or not executable"
    exit 1
fi


#determine where Prime expects to find the PDB

echo "determining Prime PDB directory ..."
echo ""

#is SCHRODINGER_PDB set?
if [ -n "$SCHRODINGER_PDB" ]; then
    echo "SCHRODINGER_PDB variable is set to:"
    echo $SCHRODINGER_PDB
    PDB_DIR=$SCHRODINGER_PDB
else
#is SCHRODINGER_THIRDPARTY set?
    if [ -n "$SCHRODINGER_THIRDPARTY" ]; then
	echo "SCHRODINGER_THIRDPARTY variable is set to:"
	echo $SCHRODINGER_THIRDPARTY
	PDB_DIR=$SCHRODINGER_THIRDPARTY/database/pdb
    else
#default to SCHRODINGER/thirdparty
	echo "using default location \$SCHRODINGER/thirdparty"
	if [ ! -n "$SCHRODINGER" ]; then
	    echo "ERROR: SCHRODINGER environment variable not set"
	    exit 1
	fi
	PDB_DIR="$SCHRODINGER/thirdparty/database/pdb"
    fi
fi

echo ""
echo "PDB directory for use with Prime:"
echo ""
echo $PDB_DIR
echo ""

#make sure the directory exists (if not ask to create it)

if [ ! -d "$PDB_DIR" ]; then
    echo "WARNING: PDB directory $PDB_DIR does not exist - create it (y/n)?"
    read answer
    if [ "$answer" = "y" ]; then
	if mkdir -p "$PDB_DIR"; then
	    echo "created PDB directory: ""$PDB_DIR"
	else
	    echo "unable to create PDB directory: ""$PDB_DIR"
	    exit 1
	fi
    else
	echo "directory creation cancelled - exit"
	exit 1
    fi
fi

#create the appropriate subdirectories (since we only mirror a subset
#of the PDB)

divided_pdb="structures/divided/pdb"
all_pdb="structures/all/pdb"
obsolete_pdb="structures/obsolete/pdb"

for subdir in "$divided_pdb" "$all_pdb" "$obsolete_pdb"
do
    dir="${PDB_DIR}/data/$subdir"
    if [ ! -d "$dir" ]; then
	echo "creating directory $dir"
	if ! mkdir -p $dir; then
	    echo "ERROR: unable to create directory $dir"
	    exit 1
	fi
    fi
done

#start the mirroring process

for subdir in "$divided_pdb" "$all_pdb" "$obsolete_pdb"
do
  ${RSYNC} -rlpt -v -z --delete --port=$PORT $SERVER::ftp_data/$subdir/ "${PDB_DIR}/data/$subdir"
done



