# where rebar3 stores build output
REBAR_BASE_DIR ?= _build
# config file used by 'run' and 'shell'
CONFIG ?= config/sys.config
# arguments passed to eunit, used by 'check'
EUNIT_ARGS ?=
# directory paths for 'install'
BINDIR ?= /usr/bin
LIBDIR ?= /usr/lib
CONFDIR ?= /etc/osmocom
SYSTEMDUNITDIR ?= /lib/systemd/system

all: build

GEN_FILES = include/S1AP-*.hrl src/S1AP-*.erl

src/S1AP-%.erl include/S1AP-%.hrl: asn1/S1AP-%.asn
	rebar3 asn compile

build: $(GEN_FILES)
	rebar3 compile

escript: $(GEN_FILES)
	rebar3 escriptize

run-escript: escript
	ERL_FLAGS='-config $(CONFIG)' $(REBAR_BASE_DIR)/default/bin/osmo-s1gw

run: shell

shell: build
	rebar3 shell --config $(CONFIG)

check: $(GEN_FILES)
	rebar3 eunit $(EUNIT_ARGS)

analyze: $(GEN_FILES)
	rebar3 dialyzer

release: $(GEN_FILES)
	rebar3 release

run-release: release
	contrib/osmo-s1gw.sh -r $(REBAR_BASE_DIR)/default/rel/osmo-s1gw -c $(CONFIG)

install: release
	install -d $(DESTDIR)$(LIBDIR)
	cp -r $(REBAR_BASE_DIR)/default/rel/osmo-s1gw $(DESTDIR)$(LIBDIR)/
	install -Dm0755 contrib/osmo-s1gw.sh \
		$(DESTDIR)$(BINDIR)/osmo-s1gw
	install -Dm0644 config/sys.config \
		$(DESTDIR)$(CONFDIR)/osmo-s1gw.config
	install -Dm0644 contrib/systemd/osmo-s1gw.service \
		$(DESTDIR)$(SYSTEMDUNITDIR)/osmo-s1gw.service

clean:
# Avoid running rebar3 clean if $(REBAR_BASE_DIR) doesn't exist, since it would try
# to fetch deps from the Internet and that may not be avaialble when in
# OBS build.
ifneq ("$(wildcard $(REBAR_BASE_DIR)/.*)", "")
	rebar3 asn clean
	rebar3 clean
	rm -rf $(REBAR_BASE_DIR)
else
	rm -f $(GEN_FILES)
endif
