#!/bin/bash -xe
# 
# Download a file by whatever means available
# 
# ======================================================================
# Antoine Le Hyaric (1,2)
# 1- CNRS, UMR 7598, Laboratoire Jacques-Louis Lions, F-75005, Paris, France
# 2- Sorbonne Universités, UPMC Univ Paris 06, UMR 7598, Laboratoire Jacques-Louis Lions, F-75005, Paris, France
# ======================================================================
# This file is part of Freefem++
#
# Freefem++ is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 2.1 of
# the License, or (at your option) any later version.
#
# Freefem++ is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with Freefem++; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
# ======================================================================
# [[shell:header\alh 'download']] (cf [[file:~/alh/bin/headeralh]])
# emacs-keywords brief="Download a file by whatever means available" default=0 freefem shellxe start=21/10/10 upmc

# $1=url
# $2=local name
# $3=BAD_CERT if the SSL certificate of the web server is wrong

if test -x /usr/bin/wget || test -x /usr/bin/wget.exe || test -x /opt/local/bin/wget
then

    opts=
    if test "$3" = BAD_CERT
    then
	opts=--no-check-certificate
    fi

    # [[man:wget]] we could use no-verbose to avoid mixing several wget outputs together when called concurrently in
    # [[file:../download/getall]], but then nothing moves while the download goes on, and the user may think that it's
    # stuck.

    wget "$1" --timeout=30 --tries=2 --output-document="$2" $opts
    ret=$?
elif test -x /usr/bin/curl
then
    curl -L "$1" --output "$2"
    ret=$?

elif test -x /usr/bin/GET
then
    GET "$1" > "$2"
    ret=$?
else
    echo FF download: No way to download files from the web
    echo FF download: Please install wget or curl or GET
exit 1
fi
if test "$ret" -eq 0 
then
  case `file $2` in
  *zip*) exit 0 ;;
  *) echo " incorrect file type => removing " $2;
     rm $2; 
    exit  1 ;;
  esac    
fi
echo "Error download $2"
exit $ret

# Local Variables:
# mode:shell-script
# ispell-local-dictionary:"british"
# coding:utf-8
# eval:(flyspell-prog-mode)
# eval:(outline-minor-mode)
# End:
# LocalWords: emacs
