#!/bin/sh
#
# get -- get files or the current directory, to FARMACHINE by ssh
#
[ -n "$echo" ] && set -x

USAGE='get [-f] [-x] [file2] ...'

FORCE=false
NONEXEC=false

while true
do
  case "$1" in
      -f)
	  FORCE=true
	  shift
	  ;;
      -x)
	  NONEXEC=true
	  shift
	  ;;
      -*)
	  echo "$USAGE" >&2
	  exit 2
	  ;;
      *)
	  break
	  ;;
  esac
done

ME='leavens'
FARMACHINE='larch.cs.iastate.edu'
AWAY="$FARMACHINE:/home/bambam/$ME"

STATUS=0

# get part of directory name below $HOME or $ALTHOME
fulldir=`pwd`

case "$fulldir" in
$HOME)
	below=.
	;;
*)
	below=`expr $fulldir : $HOME/'\(.*\)'`
	;;
esac

awaybelow="$below"

case "$below" in
0|'')
   echo "can't update $fulldir, not under $HOME" >&2
   exit 1
   ;;
bin|bat)
   awaybelow="WWW/Windows/$below"
   if test $# -le 0
   then
       echo "can't get all of $below" >&2
       exit 2
   fi
   ;;
*)
   ;;
esac

echo "updating `pwd` from $awaybelow on $FARMACHINE"

if test $# -gt 0
then
    for f
    do
	scp -pr "$AWAY/$awaybelow/$f" . || STATUS=1
	if $NONEXEC
	then chmod a-x,o-w $f
	else chmod o-w $f
	fi
    done
else
   SHIP='shipping.zip'
   HEREFILE="$HOME/temp/$SHIP"
   AWAYFILE="$AWAY/temp/$SHIP"
   ssh "$FARMACHINE" rm -f '$HOME/temp/'"$SHIP" '&&' zip -r -q -9 '$HOME/temp/'"$SHIP" "$awaybelow"
   if scp -p "$AWAY/temp/$SHIP" "$HEREFILE"
   then
       ssh "$FARMACHINE" rm -f '$HOME/temp/'"$SHIP"
       if $FORCE
       then
	   rm -fr *
	   find . -type d -a \! -name '.' -exec rm -fr '{}' ';'
	   find . -type f -exec rm -f '{}' ';'
       fi
       cd "$HOME"
       unzip -q "$HEREFILE"
       if $NONEXEC
       then chmod -R a-x,o-w "$below"
       else chmod -R o-w "$below"
       fi
       rm -f "$HEREFILE"
   else
       STATUS=1
   fi
fi

exit $STATUS
