REVISION = 4

cflags   = $(CFLAGS) $(CPPFLAGS)
ldflags  = $(LDFLAGS) $(cflags) -static

cflags  += -Wall -Wmissing-prototypes -Wformat=2 -Wshadow -pipe
ifdef REVISION
cflags  += -DREVISION=$(REVISION)
endif

CLIENT   = sbrsh
DAEMON   = sbrshd
EXPORTFS = sb-exportfs

ifdef DEBUG
cflags  += -g -DDEBUG
else
cflags  += -O2 -fomit-frame-pointer -DNDEBUG
endif

COMMON_OBJECTS = buffer.o common.o mount.o protocol.o
COMMON_HEADERS = buffer.h common.h mount.h protocol.h types.h

.PHONY: all
all: $(CLIENT) $(DAEMON) $(EXPORTFS)

$(CLIENT): client.o config.o $(COMMON_OBJECTS)
	$(CC) -o $@ $^ $(ldflags) $(cl_libs)

$(DAEMON): daemon.o fakeroot.o ident.o $(COMMON_OBJECTS)
	$(CC) -o $@ $^ $(ldflags) -lutil

$(EXPORTFS): sb-exportfs.o common.o config.o
	$(CC) -o $@ $^ $(ldflags)

.PHONY: clean
clean:
	rm -f $(CLIENT) $(DAEMON) $(EXPORTFS) *.o

.c.o:
	$(CC) $(cflags) -c -o $*.o $*.c

client.o:      client.c      $(COMMON_HEADERS) client.h config.h
	$(CC) $(cflags) $(cl_include) -c -o $@ $<

daemon.o:      daemon.c      $(COMMON_HEADERS) daemon.h fakeroot.h ident.h
common.o:      common.c      $(COMMON_HEADERS)
protocol.o:    protocol.c    $(COMMON_HEADERS)
buffer.o:      buffer.c      $(COMMON_HEADERS)
mount.o:       mount.c       $(COMMON_HEADERS)
config.o:      config.c      $(COMMON_HEADERS)
fakeroot.o:    fakeroot.c    $(COMMON_HEADERS)
ident.o:       ident.c       ident.h
sb-exportfs.o: sb-exportfs.c types.h common.h config.h

TAGS: *.[ch]
	etags -o $@ $^


CVSROOT = :ext:$(USER)@scratchbox.org:/cvsroot/scratchbox

.PHONY: source-tarball

#
# Make source tarball from given darcs repository
#
# note the ugly kludge to set correct REVISION
#
source-tarball:
	@(if ! darcs changes -t . --last=1 | grep -q . ; then \
		echo "You are trying to build source tarball from untagged revision."; \
		echo "This is doomed to fail. please refer to README."; \
		exit; \
	fi && \
	VERSION=`darcs changes | grep tagged | head -1 | sed 's/^[^_]*_//' | tr '_' '.' | tr -d ' '` && \
	REVISION=`echo $$VERSION | cut -d '.' -f2-` && \
	TMP=$$(mktemp -d tmp.XXXXXX) && \
	cd $$TMP && \
	darcs get .. && \
	cd sbrsh && \
	mv Makefile Makefile.orig && \
	echo -e "REVISION = $$REVISION\n" > Makefile && \
	cat Makefile.orig >> Makefile && \
	darcs record -a -m "kludge" && \
	darcs dist --dist-name sbrsh-$$VERSION && \
	mv sbrsh-$$VERSION.tar.gz ../.. && \
	cd ../.. && \
	rm -rf $$TMP && \
	md5sum "sbrsh-$$VERSION.tar.gz")

.PHONY: ipk
ipk: sbrshd
	rm -rf ipkg/build

	install -d ipkg/build/CONTROL
	sed s/'<VERSION>'/`head -n1 debian/changelog | cut -d'(' -f2 | cut -d')' -f1`/ ipkg/control.in > ipkg/build/CONTROL/control
	install -m 755 ipkg/postinst ipkg/build/CONTROL/
	install -m 755 ipkg/postrm ipkg/build/CONTROL/

	install -d ipkg/build/usr/sbin
	install -m 755 sbrshd ipkg/build/usr/sbin/

	ipkg-build ipkg/build
	rm -rf ipkg/build

.PHONY: deb
deb: sbrshd
	dpkg-buildpackage -rfakeroot -b
