#!/usr/bin/env bash
# -xe

############################################################################
# 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 3 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, see <http://www.gnu.org/licenses/>.          #
############################################################################
# SUMMARY : Download a file by whatever means available
# LICENSE : LGPLv3
# ORG     : LJLL Universite Pierre et Marie Curie, Paris, FRANCE
# AUTHORS : Antoine Le Hyaric
# E-MAIL  : ...

# $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:../3rdparty/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" --connect-timeout 30
    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
