HTSDIR=./htslib
HTSLIB_LIBDIR="${R_PACKAGE_DIR}/lib${R_ARCH}"
HTSLIB_INCLUDEDIR="${R_PACKAGE_DIR}/include"

R_CC=`"${R_HOME}/bin/R" CMD config CC`
R_CFLAGS=`"${R_HOME}/bin/R" CMD config CFLAGS`
R_CPICFLAGS=`"${R_HOME}/bin/R" CMD config CPICFLAGS`
R_LDFLAGS=`"${R_HOME}/bin/R" CMD config LDFLAGS`
R_CPPFLAGS=`"${R_HOME}/bin/R" CMD config CPPFLAGS`
R_CPP=`"${R_HOME}/bin/R" CMD config CPP`

R_BIN="${R_HOME}/bin/R"
ON_SNOWLEOPARD=`echo 'if(Sys.info()["sysname"] == "Darwin" && \
    grepl("^10.8", Sys.info()["release"])) cat("1") else cat("0")' |\
    ${R_BIN} --vanilla --slave`

.PHONY: all clean Rinstall

all: $(SHLIB)

$(SHLIB): Rhtslib.o

# always run Rinstall so we never skip copying libraries & headers
# into destination; otherwise, a user could R CMD INSTALL Rhtslib,
# then subsequently remove the package, then try R CMD INSTALL Rhtslib
# again--in which case the library and headers would not be
# reinstalled
Rhtslib.o: Rinstall

# Redirect to /dev/null so user doesn't see potentially confusing
# output from libtool about options for linking to the libraries. (The
# instructions are not relevant for our purposes.)
Rinstall: $(HTSDIR)/libhts.la
	@echo "installing libraries and headers..."
	@cd $(HTSDIR)/ && $(MAKE) \
	    install-libLTLIBRARIES \
	    install-includeHEADERS > /dev/null
	@rm -fr "${R_PACKAGE_DIR}/lib/libhts.la" > /dev/null

## yes, need to 'cd' into $(HTSDIR) for each command
$(HTSDIR)/libhts.la:
        ## if on Snow Leopard, touch all files so it doesn't think it
        ## needs to rerun aclocal & co.
	@if [ ${ON_SNOWLEOPARD} == "1" ]; then find . | xargs touch ; fi
        ## run ./htslib/configure
	@echo "running configuration..."
	cd $(HTSDIR)/ && ./configure --disable-dependency-tracking \
	--prefix="${R_PACKAGE_DIR}" \
	CC="${R_CC}" CFLAGS="${R_CFLAGS} ${R_CPICFLAGS}" \
	LDFLAGS="${R_LDFLAGS}" CPPFLAGS="${R_CPPFLAGS}" CPP="${R_CPP}"
	@echo "buildling library..."
	cd $(HTSDIR)/ && $(MAKE)

## files generated by configure
CONFIGURE_GEN_FILES= \
    $(HTSDIR)/autom4te* \
    $(HTSDIR)/config.h \
    $(HTSDIR)/config.log \
    $(HTSDIR)/config.status \
    $(HTSDIR)/libtool \
    $(HTSDIR)/lib/Makefile \
    $(HTSDIR)/Makefile \
    $(HTSDIR)/test/Makefile \
    $(HTSDIR)/stamp-h1 \
    $(HTSDIR)/cram/.deps

## removing configure-generated files MUST come after running
## clean-recursive in HTSDIR, since said recursive Makefiles specify
## what to clean
clean:
	rm -f *.o *.a
	-cd $(HTSDIR) && $(MAKE) distclean-recursive && cd ..
	rm -fr $(CONFIGURE_GEN_FILES)

shlib-clean: clean
