#! /bin/sh
#
#   Locate urlget.py
#
if [ -x urlget.py ]; then
  URLGET=./urlget.py
fi
if [ "$URLGET" = "" ]; then
  for i in $PATH
  do
    if [ -x $i/urlget.py ]; then
      URLGET=$i/urlget.py
      break
    fi
  done
fi
if [ "$URLGET" = "" ]; then
  if [ "$PETSC_DIR" != "" ]; then
    if [ -d $PETSC_DIR ]; then
      if [ ! -x $PETSC_DIR/bin/urlget.py ]; then
#       echo PETSC_DIR is set but cannot locate bin/urlget.py
        PETSC_DIR=""
      fi
    else
#     echo PETSC_DIR is set but does not point to valid directory
      PETSC_DIR=""
    fi
  else
    if [ -x bin/urlget.py ]; then
      PETSC_DIR=`pwd`
    fi
  fi
  if [ "$PETSC_DIR" != "" ]; then
    URLGET=$PETSC_DIR/bin/urlget.py
  fi
fi

#
#  Check if urlget.py works
#
if [ "$URLGET" != "" ]; then
  $URLGET -v > /dev/null 2>&1
  if [ $? -ne 0 ]; then
#
#   Find Python
#
    for i in python python1.5 python2 /usr/local/bin/python
    do
      $i -help  > /dev/null 2>&1
      if [ $? -ne 127 ]; then
        PYTHON=$i
        break
      fi
    done
    if [ "$PYTHON" != "" ]; then
#
#   Patch urlget.py to use correct python
#
      sed -e "s?python1.4?$PYTHON?g" $URLGET > .tmp
      mv -f .tmp $URLGET
      chmod ugo+x $URLGET

#
#   Check if urlget.py works
#
      $URLGET -v > /dev/null 2>&1
      if [ $? -ne 0 ]; then
#      echo "Could not get python to work with urlget.py on your machine"
        URLGET=""
      fi
    else
#      echo "Could not locate python on machine"
      URLGET=""
    fi
  fi
fi
#
#
#
if [ "$URLGET" != "" ]; then
  $URLGET $*
  exit
fi
#
#  Try to use wget
#
#   Does wget exist and seem to work?
#
wget -help > /dev/null 2>&1
if [ $? -eq 0 ]; then
  if [ "$1" = "-v" ]; then
    exit 0
  fi
#
#  Get the requested file
#
  flag1=`echo $file | sed -e "s?http://[-a-zA-Z_0-9.]*.gz?yes?g"`
  flag2=`echo $file | sed -e "s?ftp://[-a-zA-Z_0-9.]*.gz?yes?g"`

  if [ "$flag1" = "yes" -o "$flag2" = "yes" ] ; then 
    wget -r $* > /dev/null 2>&1
    if [ $? -ne 0 ]; then
      exit 0
    fi
  else
    cp -f $* .
  fi

  file=`basename $*`
#
#  uncompress it if it is gziped
#

  flag=`echo $file | sed -e "s/[-a-zA-Z_0-9.]*.gz/yes/g"`
  if [ "$flag" = "yes" ] ; then
    gunzip -f $file > /dev/null 2>&1
    file=`echo $file | sed -e "s/\([-a-zA-Z_0-9.]*\).gz/\1/g"`
  fi
  echo $file
  exit 0
fi


