#
# Project Home:
# ============
#   https://github.com/riscv/riscv-openocd
#
# Clone:
# =====
#   git clone https://github.com/riscv/riscv-openocd.git
#

url        = https://github.com/riscv

#
# List of tags to be extracted (branch riscv):
# ====================================================================
#
#                                               hash | version
#            ----------------------------------------+---------
revisions  = af786c0eca6a3b845c8e6f2bb41fdc4ecbe83748:0.12.0


repo_name  = riscv-openocd
pkg_name   = riscv-openocd
suffix     = tar.xz

git_repo   = .git_clone

versions   = $(foreach tag, $(revisions), $(shell echo $(tag) | cut -f 2 -d ':'))

tarballs   = $(addsuffix .tar.xz, $(addprefix $(pkg_name)-, $(versions)))
sha1s      = $(addsuffix .sha1sum, $(tarballs))

TARGETS = repository_clean


all: $(TARGETS)

.PHONY: downloads_clean repository_clean

$(git_repo):
	@echo -e "\n======= Clone $(repo_name).git repository =======\n"
	@rm -rf $(repo_name)
	@git clone $(url)/$(repo_name).git $(repo_name)
	@touch $@

$(tarballs): $(git_repo)
	@for revision in $(revisions) ; do \
	  hash=`echo $$revision    | cut -f 1 -d ':'` ; \
	  version=`echo $$revision | cut -f 2 -d ':'` ; \
	  if [ ! -f $(pkg_name)-$$version.$(suffix) ]; then \
	    echo -e "\n======= Creating '$(pkg_name)-$$version.$(suffix)' snapshot =======" ; \
	    ( cp -r $(repo_name) $(pkg_name)-$${version} ; \
	      cd $(pkg_name)-$${version} ; \
	      git checkout -b v$${version} $${hash} ; \
	      sed -i "s|\+dev||" configure.ac ; \
	      ./bootstrap ; \
	      rm -rf autom4te.cache ; \
	      find . -type f \( -name '.checkpatch.conf' -o -name '.git*' -o -name '.travis.yml' \) -exec rm -rf {} \; ; \
	      find . -type d -name '.git*' -exec rm -rf {} \; 2>/dev/null ; \
	    ) ; \
	    tar cJf $(pkg_name)-$${version}.tar.xz $(pkg_name)-$${version} ; \
	    rm -rf $(pkg_name)-$${version} ; \
	  fi ; \
	done

$(sha1s): %.tar.xz.sha1sum : %.tar.xz
	@for tarball in $< ; do \
	  echo -e "\n======= Calculation the '$$tarball' sha1sum =======" ; \
	  sha1sum --binary $$tarball > $$tarball.sha1sum ; \
	done

repository_clean: $(sha1s)
	@echo -e "\n======= Remove cloned $(repo_name).git repository =======\n"
	@rm -rf $(git_repo) $(repo_name)

downloads_clean:
	@rm -rf $(tarballs) $(sha1s)
	@rm -rf $(git_repo) $(repo_name)
