#! /bin/sh -x

SUBDIR=$1

PCMCIA_HTTP=http://www.piercefuller.com
PCMCIA_DIR=oldibm/1401/diagman/full
WGET_ARGS="--quiet --passive-ftp --timestamping"

/bin/rm -f index.html
wget --dont-remove-listing $WGET_ARGS $PCMCIA_DIR/$SUBDIR/

if [ -f index.html ]; then
   if [ `wc -l index.html | awk '{print $1}'` -ne 0 ]; then

      /bin/rm -f LIST.pcmcia-cs
      grep HREF= index.html \
	|awk -F\< '{print $3}' | awk -F\" '{print $2}' \
	| grep -v / | grep -v "Parent Directory" \
		> LIST.pcmcia-cs
      touch LIST.pcmcia-cs.$SUBDIR
      diff LIST.pcmcia-cs LIST.pcmcia-cs.$SUBDIR > LIST.diffs

      if [ `wc -l LIST.diffs | awk '{print $1}'` -ne 0 ]; then

	 # Get files automatically!

	 /bin/rm -f LIST.get
	 grep \< LIST.diffs | tr -d \< > LIST.get
	 if [ `wc -l LIST.get | awk '{print $1}'` -ne 0 ]; then
		  for FILE in `cat LIST.get`; do
			  wget $WGET_ARGS $PCMCIA_DIR/$SUBDIR/$FILE
			  chmod u+rw,go-w $FILE
		  done
	 fi
	 /bin/rm -f LIST.get

	 # Don't remove files automatically!

	 grep \> LIST.diffs | tr -d \> > LIST.remove.$SUBDIR
	 if [ `wc -l LIST.remove.$SUBDIR | awk '{print $1}'` -eq 0 ]; then
		  /bin/rm -f LIST.remove.$SUBDIR
	 #else
	 #	for FILE in `cat LIST.remove.$SUBDIR`; do
	 #		/bin/rm -f $FILE
	 #	done
	 fi

	 /bin/mv LIST.pcmcia-cs LIST.pcmcia-cs.$SUBDIR
#	 mail -s "$SUBDIR PCMCIA Updates" rpt@korak.jpl.nasa.gov < LIST.diffs

      fi
      /bin/rm -f LIST.pcmcia-cs LIST.diffs
   fi
   /bin/rm -f index.html
fi
