# Root of installation tree
PREFIX = /home/usel/tmp
# Path where the executables are installed
BINDIR = $(PREFIX)/bin
# Path where the manual pages are installed
MANDIR = $(PREFIX)/share/man
# Path to Midnight Commander extfs
MCEXTFSDIR = $(PREFIX)/share/mc/extfs

# Name of package
PACKAGE = torrentutils
# Version of package
VERSION = 0.3.0
# Authors of package
AUTHORS = Oskar Liljeblad

# Directory in archive created by `make dist'
DISTDIR = $(PACKAGE)-$(VERSION)
# Files to include in distribution
DISTFILES = \
	torrenttool.in torrenttool.1 \
	defrag.in defrag.1 \
	bcode.pl \
	torrentmcfs.in \
	torrentutils.spec.in \
	README COPYING NEWS TODO \
	Makefile

tmp_diff_dir = tmpdist

.PHONY: install dist distdiff all clean debian rpm

all: torrenttool torrentmcfs defrag torrentutils.spec

torrenttool: torrenttool.in bcode.pl
torrentmcfs: torrentmcfs.in bcode.pl
defrag: defrag.in
torrentutils.spec: torrentutils.spec.in

%: %.in
	cat $^ | sed "s,@VERSION@,$(VERSION),; \
		      s,@PACKAGE@,$(PACKAGE),; \
		      s,@AUTHORS@,$(AUTHORS)," > $@
	if [[ "$@" != *.spec ]]; then chmod a+x $@; fi

install: all
	install -d $(BINDIR) $(MANDIR)/man1
	install -m 755 torrenttool $(BINDIR)/torrenttool
	install -m 755 defrag $(BINDIR)
	rm -f tmp.torrenttool.$$
	install -m 644 torrenttool.1 $(MANDIR)/man1
	install -m 644 defrag.1 $(MANDIR)/man1
	install -d $(MCEXTFSDIR)
	install -m 755 torrentmcfs $(MCEXTFSDIR); \
	if [ -f $(MCEXTFSDIR)/extfs.ini ]; then \
	  grep '^torrentmcfs$$' $(MCEXTFSDIR)/extfs.ini || echo 'torrentmcfs' >> $(MCEXTFSDIR)/extfs.ini; \
	else \
	  echo "$(MCEXTFSDIR) does not exist. Not installing MC extfs support."; \
	fi

clean:
	rm -f torrenttool torrentmcfs defrag torrentutils.spec
	rm -f build-stamp debian/$(PACKAGE).{postinst,prerm}.debhelper
	rm -f debian/$(PACKAGE).substvars debian/files debian/substvars
	rm -rf debian/$(PACKAGE)

debian:
	dpkg-buildpackage -rfakeroot -us -uc -sd -b

rpm: $(PACKAGE).spec
	rpm -bb --clean $(PACKAGE).spec

dist:
	rm -rf $(DISTDIR)
	mkdir $(DISTDIR) $(DISTDIR)/tests
	cp $(DISTFILES) $(DISTDIR)
	cp -r tests/tools tests/README tests/buildtests tests/runtests $(DISTDIR)/tests
	chmod a-s $(DISTDIR)
	tar cvfz $(DISTDIR).tar.gz $(DISTDIR)
	rm -rf $(DISTDIR)

distdiff:
	rm -rf $(tmp_diff_dir) && \
	cur=$(DISTDIR) && \
	prev=`find $(PACKAGE)-*|egrep -v "^$$cur.tar.gz\$$"|sort -r|head -1|sed 's/\.tar\.gz$$//'` && \
	mkdir $(tmp_diff_dir) && \
	cd $(tmp_diff_dir) && \
	tar xfz ../$$prev.tar.gz && \
	tar xfz ../$$cur.tar.gz && \
	find -type l | xargs rm && \
	diff -ruN $$prev $$cur | pager && \
	cd - && \
	rm -rf $(tmp_diff_dir);
