#
#  Copyright (c) 2008-2014,
#  Reto Buerki <reet@codelabs.ch>
#
#  This file is part of PCSC/Ada.
#
#  PCSC/Ada is free software; you can redistribute it and/or modify
#  it under the terms of the GNU Lesser General Public License as published
#  by the Free Software Foundation; either version 2.1 of the License, or
#  (at your option) any later version.
#
#  PCSC/Ada is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU Lesser General Public License for more details.
#
#  You should have received a copy of the GNU Lesser General Public License
#  along with PCSC/Ada; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
#  MA  02110-1301  USA
#

PREFIX ?= $(HOME)/libraries
INCDIR  = $(PREFIX)/share/ada/adainclude/pcscada
ALIDIR  = $(PREFIX)/lib/ada/adalib/pcscada

INSTALL = install

MAJOR   = 0
MINOR   = 7
REV     = 6
VERSION = $(MAJOR).$(MINOR).$(REV)
PCSCADA = libpcscada-$(VERSION)

LIBRARY_KIND = dynamic

SOURCEDIR  = src
DOCDIR     = doc/html
ALI_FILES  = lib/$(LIBRARY_KIND)/*.ali
SO_LIBRARY = libpcscada.so.$(VERSION)
A_LIBRARY  = libpcscada.a

TARBALL = $(PCSCADA).tar.bz2

NUM_CPUS ?= 1

# GNAT_BUILDER_FLAGS, ADAFLAGS, LDFLAGS and GNATFLAGS may be overridden in the
# environment or on the command line.
GNAT_BUILDER_FLAGS ?= -R -j$(NUM_CPUS)
GNATFLAGS          ?= ${GNAT_BUILDER_FLAGS}
# GMAKE_OPTS should not be overridden because -p is essential.
GMAKE_OPTS = -p $(GNATFLAGS) \
  $(foreach v,ADAFLAGS LDFLAGS LIBRARY_KIND VERSION,'-X$(v)=$($(v))')

all: build_lib

build_lib:
	gprbuild $(GMAKE_OPTS) -Ppcscada_lib -XLIBRARY_KIND=$(LIBRARY_KIND)

build_utests:
	gprbuild $(GMAKE_OPTS) -Ppcscada_utests -XLIBRARY_KIND=static

build_itests:
	gprbuild $(GMAKE_OPTS) -Ppcscada_itests -XLIBRARY_KIND=static

build_examples:
	gprbuild $(GMAKE_OPTS) -p -Ppcscada_examples -XLIBRARY_KIND=static

clean:
	@rm -rf obj/*
	@rm -rf lib/*
	$(MAKE) -C doc clean

distclean:
	@rm -rf obj
	@rm -rf lib
	@rm -rf $(DOCDIR)

# run unit tests
utests: build_utests
	@obj/utests/runner

# run 'integration' tests
# you need a reader and smartcard for this to work
itests: build_itests
	@obj/itests/test_pcscada

examples: build_examples

install: install_lib install_$(LIBRARY_KIND)

install_lib: build_lib
	@mkdir -p $(INCDIR)
	@mkdir -p $(ALIDIR)
	$(INSTALL) -m 644 $(SOURCEDIR)/* $(INCDIR)
	$(INSTALL) -m 444 $(ALI_FILES) $(ALIDIR)

install_static:
	mkdir -p $(PREFIX)/lib
	$(INSTALL) -m 644 lib/$(LIBRARY_KIND)/$(A_LIBRARY) $(PREFIX)/lib

install_dynamic:
	mkdir -p $(PREFIX)/lib
	$(INSTALL) -m 644 lib/$(LIBRARY_KIND)/$(SO_LIBRARY) $(PREFIX)/lib
	@cd $(PREFIX)/lib && ln -sf $(SO_LIBRARY) libpcscada.so

doc:
	@$(MAKE) -C doc

dist:
	@echo "Creating release tarball $(PCSCADA) ... "
	@git archive --format=tar HEAD --prefix $(PCSCADA)/ | bzip2 > $(TARBALL)

.PHONY: doc
