# -*- mode: Makefile -*-

mypath = $(dir $(realpath $(firstword $(MAKEFILE_LIST))))
topsrcdir = $(shell git rev-parse --show-toplevel)
GITREV = $(shell git describe --always --tags)
GITREV_FOR_PKG = $(shell echo "$(GITREV)" | sed -e 's,-,\.,g' -e 's,^v,,')

PACKAGE ?= $(shell basename $(topsrcdir))
DISTGIT_NAME ?= $(PACKAGE)
DISTGIT ?= https://src.fedoraproject.org/rpms/$(DISTGIT_NAME)
SPEC ?= $(topsrcdir)/$(DISTGIT_NAME).spec

PKG_VER = $(PACKAGE)-$(GITREV_FOR_PKG)
PKG_CLIENT_VER = $(PACKAGE)-client-$(GITREV_FOR_PKG)

dist-snapshot:
	if ! test -f $(PKG_VER).tar.xz; then \
	  $(mypath)/make-git-snapshot.sh "$(topsrcdir)" "$(PKG_VER)" "$(GITREV)" && \
	  rm -f $(PKG_VER).tar.xz && \
	  xz $(PKG_VER).tar; \
  fi

srpm: dist-snapshot
	if test -f "$(SPEC)"; then \
	   sed -e "s,^Version:.*,Version: $(GITREV_FOR_PKG)," $(SPEC) > $(DISTGIT_NAME).spec && \
	   $(mypath)/rpmbuild-cwd -bs $(DISTGIT_NAME).spec ; \
	else \
	  test -d $(DISTGIT_NAME) || git clone --depth=1 $(DISTGIT) && \
    mv $(PKG_VER).tar.xz $(DISTGIT_NAME) && \
    origdir=$$(pwd); \
	  cd $(DISTGIT_NAME) && \
		git stash && git pull -r && \
	  sed -i -e '/^Patch/d' -e "s,^Version:.*,Version: $(GITREV_FOR_PKG)," $(DISTGIT_NAME).spec && \
    rm -f *.src.rpm && \
	  $(mypath)/rpmbuild-cwd -bs $(DISTGIT_NAME).spec && mv *.src.rpm $${origdir}; \
	fi

rpm: srpm
	./rpmbuild-cwd --rebuild $(PKG_VER)*.src.rpm
