# Makefile for bsdiskinfo project
# Target platform: FreeBSD bmake standard

SHLIB_MAJOR=	0
SHLIB_MINOR=	1
VERSION=	$(SHLIB_MAJOR).$(SHLIB_MINOR)

LIB_NAME=	libbsdiskinfo.so
LIB_SONAME=	$(LIB_NAME).$(SHLIB_MAJOR)
LIB_SOLINK=	$(LIB_NAME).$(VERSION)
CLI_NAME=	bsdiskinfo-cli

CC?=		cc
CFLAGS+=	-O2 -Wall -fPIC -I./include
LDFLAGS+=	-shared -lcam -Wl,-soname,$(LIB_NAME).$(SHLIB_MAJOR)

LIB_SRCS=	src/libbsdiskinfo.c
CLI_SRCS=	src/cli.c

TARGETS=	$(LIB_SOLINK) $(LIB_NAME)

.ifndef WITHOUT_CLI
TARGETS+=	$(CLI_NAME)
.endif

# Default execution entry point
all: $(TARGETS) modules_all

$(LIB_SOLINK): $(LIB_SRCS)
	$(CC) $(CFLAGS) $(LIB_SRCS) $(LDFLAGS) -o $(LIB_SOLINK)
	ln -sf $(LIB_SOLINK) $(LIB_SONAME)

$(LIB_NAME): $(LIB_SOLINK)
	ln -sf $(LIB_SOLINK) $(LIB_NAME)

$(CLI_NAME): $(CLI_SRCS) $(LIB_SOLINK)
	$(CC) $(CFLAGS) $(CLI_SRCS) -L. -lbsdiskinfo -lcam -Wl,-rpath,. -o $(CLI_NAME)

# Conditional compilation path for sub-modules
modules_all: $(LIB_SOLINK) $(LIB_NAME)
.ifndef WITHOUT_LUA
	@if [ -d modules/lua ]; then \
		cd modules/lua && $(MAKE) LUA_VER=$(LUA_VER); \
	fi
.endif
.ifndef WITHOUT_PERL
	@if [ -d modules/perl ]; then \
		cd modules/perl && if [ ! -f Makefile ]; then perl Makefile.PL; fi && $(MAKE); \
	fi
.endif

clean:
	rm -f $(LIB_NAME) $(LIB_SONAME) $(LIB_SOLINK) $(CLI_NAME)
	@if [ -d modules/lua ]; then \
		cd modules/lua && $(MAKE) clean; \
	fi
	@if [ -d modules/perl ]; then \
		cd modules/perl && if [ -f Makefile ]; then $(MAKE) realclean; fi && rm -f ppport.h Makefile.old; \
	fi

install: $(LIB_SOLINK)
	mkdir -p $(DESTDIR)/usr/local/lib
	mkdir -p $(DESTDIR)/usr/local/include
	install -m 755 $(LIB_SOLINK) $(DESTDIR)/usr/local/lib/
	ln -sf $(LIB_SOLINK) $(DESTDIR)/usr/local/lib/$(LIB_NAME)
	install -m 644 include/bsdiskinfo.h $(DESTDIR)/usr/local/include/

.ifndef WITHOUT_CLI
	mkdir -p $(DESTDIR)/usr/local/sbin
	install -m 755 $(CLI_NAME) $(DESTDIR)/usr/local/sbin/
.endif
.ifndef WITHOUT_LUA
	@if [ -d modules/lua ]; then \
		cd modules/lua && $(MAKE) install DESTDIR=$(DESTDIR) PREFIX=$(PREFIX) LUA_VER=$(LUA_VER); \
	fi
.endif
.ifndef WITHOUT_PERL
	@if [ -d modules/perl ]; then \
		cd modules/perl && $(MAKE) install DESTDIR=$(DESTDIR); \
	fi
.endif

.PHONY: all clean install modules_all

