# 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

###########################################################
# download and unpack a package
# $(1) = package name
# $(2) = package URL
# $(3) = directory name
# $(4) = plugin/code name
###########################################################

define download_and_unpack
  @(if test ! -s ../archive/`echo "$(2)" | sed 's/.*\///;s/.*=//'` && test ! -e ../$(3) ; then \
  wget -O ../archive/`echo "$(2)" | sed 's/.*\///;s/.*=//'` $(2) > /dev/null 2>&1; \
  if test "`echo $$?`" -ne "0" ; then \
  curl -o ../archive/`echo "$(2)" | sed 's/.*\///;s/.*=//'` $(2) > /dev/null 2>&1; \
  if test "`echo $$?`" -ne "0" ; then \
  echo "*** Unable to download $(4). 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 $(2)" ; \
  exit 1 ; fi ; fi ; fi)
  if test ! -e ../$(3); then \
  (gzip -dc ../archive/`echo "$(2)" | sed 's/.*\///;s/.*=//'` | \
    (cd ../ ; tar -xvf - ) ) ; \
  if test "`echo $$?`" -ne "0" ; then \
  echo "*** Unable to download $(2)." ; \
  echo "*** Verify that the url is correct." ; \
  exit 1 ; \
  else \
  (cd ../ ; ln -s $(1) $(3)) ; fi ; fi
endef

###########################################################
# update submodule
# $(1) = package upper directory with respect to TOPDIR
# $(2) = package name/directory
# if the work directory is git cloned, call git submodule update
# if the work directory is from tarball, git init if the folder was not initialized previously.
###########################################################

define update_submodule
  @(echo initializing $(1)/$(2) submodule ...)
  @(if test ! `command -v git` ; then echo "git not found. Please make sure git is installed."; exit 1; fi)
  @(if test -d $(TOPDIR)/.git ; then \
      cd $(TOPDIR) && git submodule update --depth 1 -- $(1)/$(2) && cd -; \
    else \
      if test -e $(TOPDIR)/$(1)/$(2)/.git ; then \
        echo "  $(1)/$(2)/.git exists. Skipping initialization."; \
        echo "  If you would like to force a reinitializaton, remove $(1)/$(2) subdirectory."; \
      else \
        RECORD_HASH=`grep $(2) $(TOPDIR)/$(1)/submodule_commit_hash_records | awk '{print $$1}'`; \
        SUBMODULE_URL=`git config --file $(TOPDIR)/.gitmodules --get submodule.$(1)/$(2).URL`; \
        git init $(TOPDIR)/$(1)/$(2) ; cd $(TOPDIR)/$(1)/$(2) ; \
        git remote add origin $${SUBMODULE_URL} ; \
        git fetch --depth 1 origin $${RECORD_HASH} ; \
        git checkout -b recorded_HEAD FETCH_HEAD; \
      fi; \
    fi)
endef
