# Copyright (C) 2001-2016 Quantum ESPRESSO group
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License. See the file `License' in the root directory
# of the present distribution.
#
# Utilities

###########################################################
# Template function
# $(1) = package name
# $(2) = package URL
# $(3) = directory name
# $(4) = plugin/code name
###########################################################


define download_and_unpack
  package='$(1)'; \
  package_URL='$(2)'; \
  package_directory='$(3)'; \
  package_code='$(4)'; \
  package_archive=../archive/`echo "$${package}" | sed 's/.*\///;s/.*=//'`; \
  (if ! gzip -t $${package_archive} > /dev/null 2>&1; then \
     rm -fr $${package_archive} ; \
      wget -O $${package_archive} $${package_URL} > /dev/null 2>&1; \
      if [ $$? -ne 0 ]; then \
        curl -o $${package_archive} $${package_URL} > /dev/null 2>&1; \
        if [ $$? -ne 0 ]; then \
          echo "*** Unable to download $${package_code}. Test whether curl or wget is installed and working," ; \
          echo "*** if you have direct access to internet. If not, copy into archive/ the file" ; \
          echo "*** located here $${package_URL}" ; \
          exit 1 ; \
        fi; \
      fi; \
   fi \
  ); \
  echo fdfdfd ../$${package_directory}; \
  if [ $$? -eq 0 -a ! -e ../$${package_directory} ]; then \
    (gzip -dc $${package_archive} | \
    (cd ../ ; tar -xvf - )) ; \
    if [ $$? -ne 0 ]; then \
      echo "*** Unable to download $${package_URL}." ; \
      echo "*** Verify that the url is correct." ; \
      exit 1 ; \
    else \
      (cd ../ ; ln -s $${package} $${package_directory}); \
    fi; \
  fi
endef
