#!/bin/sh

# Usage: fetcher [-c] -O FILE URL

f_args="-t 3 -T 60 --passive-ftp"
f_file=
f_url=
f_help=

while [ x"$1" != x"" ] ; do
  case "$1" in
    -O )
      f_file="$2"
      shift
    ;;
    -c )
      f_args="$1 $f_args"
    ;;
    -* )
      echo "Unknown option: $1" 1>&2
      f_help=1
    ;;
    * )
      f_url=$1
  esac
  shift
done

if [ x"$f_file" = x"" -o x"$f_url" = x"" ] ; then
  echo "Missing FILE and/or URL" 1>&2
  f_help=1
fi

if [ x"$f_help" != x"" ] ; then
  echo "Usage: $0 [-c] -O FILE URL" 1>&2
  exit 1
fi

extraHeader=
if [ x"$http_proxy" != x"" ] ; then
  baseFile="$(basename "$f_file")"
  if [ x"$(basename "$f_url")" != x"$baseFile" ] ; then
    extraHeader="X-unique-cache-name: $baseFile"
  fi
fi

if [ x"$extraHeader" != x"" ] ; then
  echo "Adding '$extraHeader' to request" 1>&2
  exec wget $args -O "$f_file" --header="$extraHeader" "$f_url"
else
  exec wget $args -O "$f_file" "$f_url"
fi
