PROJECT=scmxx
VERSION=$(shell ./configure --version | grep ^$(PROJECT) | cut -f 3 -d " ")
OLDDIR=$(shell basename `readlink -f .`)
NEWDIR=$(PROJECT)-$(VERSION)

.PHONY: all
all: tar_gz tar_bz2 rpm exe

.PHONY: prepare
prepare: Makefile.cvs
	@if [ $(OLDDIR) != $(NEWDIR) ]; then \
	  if [ ! -d ../$(NEWDIR) ]; then \
	    echo "Renaming: $(OLDDIR) => $(NEWDIR)"; \
	    mv ../$(OLDDIR) ../$(NEWDIR); \
	  else \
	    echo "ERROR: ../$(NEWDIR)  already exists"; \
	    false; \
	  fi \
	fi
	@$(MAKE) -f Makefile.cvs Makefile
	@$(MAKE) -C docs/ all
	@$(MAKE) -f Makefile.cvs clean


#
# Pure source archives
#

.PHONY: tar_gz
tar_gz: ../$(NEWDIR).tar.gz

../$(NEWDIR).tar.gz: prepare
	@echo "Building ../$(NEWDIR).tar.gz..."
	@tar --directory .. --create --gzip --file $@ $(NEWDIR)

.PHONY: tar_bz2
tar_bz2: ../$(NEWDIR).tar.bz2

../$(NEWDIR).tar.bz2: prepare
	@echo "Building ../$(NEWDIR).tar.bz2..."
	@tar --directory .. --create --bzip2 --file $@ $(NEWDIR)


#
# RPM package creation
# It can handle old (<4.1) and new (>=4.1) versions of rpm.
#

ARCH=$(shell uname -m)
RPM=$(shell which rpmbuild || which rpm)
RPM_ROOT=$(shell echo $(shell $(RPM) --showrc | grep -E "_topdir[[:space:]]+") | cut -f 3 -d " ")

.PHONY: rpm
rpm: ../$(NEWDIR).tar.bz2
# using RPM as user really SUCKS :-(
# The RPM programmers never learned about good command line options, obviously.
	@test $(RPM) || echo "You need rpmbuild or rpm to build the .rpm files." 
# actually build the package files
	$(RPM) -ta --clean --target $(ARCH) $<
	@if [ "$(RPM_ROOT)" ]; then \
	  mv $(RPM_ROOT)/RPMS/$(ARCH)/$(NEWDIR)-*.$(ARCH).rpm ..; \
	  mv $(RPM_ROOT)/SRPMS/$(NEWDIR)-*.src.rpm ..; \
	else \
	  echo "You have to manually move the packages from your rpm build root."; \
	fi

#
# Debian package creation.
# You need a debian/ subdir, e.g. the one from Debian.
#

.PHONY: deb
deb: debian/rules
	-dpkg-buildpackage -rfakeroot -b -uc -us


#
# Windows installer creation using Inno Setup
# Define $INNODIR if the Inno Setup installation dir is not in your path.
# This variable MUST have a trailing (back)slash.
#

SYSTEM_TYPE=$(shell ./config.guess | cut -f 3 -d "-")
ISSFILE=winsetup-$(SYSTEM_TYPE).iss
CONFIGURE=./configure
ifeq '$(SYSTEM_TYPE)' 'cygwin'
#compiling with CygWin
EXELIBS=cygwin1.dll cygiconv-2.dll cygintl-3.dll
else
#compiling with MingW32 or cross-compiling
ISSFILE=winsetup-mingw.iss
EXELIBS=libiconv-2.dll libintl-3.dll
ifeq '$(SYSTEM_TYPE)' 'linux'
#this is for Debians mingw32 package
GCC_EXEC_PREFIX=i586-mingw32msvc-
CONFIGURE=cross-configure
endif
endif

%.dll:
	test "$(shell which $@)" && cp $(shell which $@) .

$(PROJECT).exe:
	$(MAKE) -f Makefile.cvs
	$(CONFIGURE)
	$(MAKE) clean
	$(MAKE)

UNIX2DOS=unix2dos
ISCC=$(INNODIR)iscc
.PHONY: exe
exe: $(ISSFILE) $(PROJECT).exe $(EXELIBS)
	$(UNIX2DOS) docs/README_WIN32.txt
#Does stripping work with cygwin libs?
	$(GCC_EXEC_PREFIX)strip *.exe $(EXELIBS)
	$(ISCC) /O.. $(ISSFILE)
