#!/usr/bin/make -f

export DH_VERBOSE=1
export JAVA_HOME=$(shell bin/find-java.sh 1.8 11.9999)
export PACKAGE_NAME="opennms-sentinel"

export SENTINEL_PREFIX=/usr/share/sentinel
export RUNTIME_PREFIX=/var/lib/sentinel
export REPO_PREFIX=$(SENTINEL_PREFIX)/repositories
export LOGDIR=/var/log/sentinel
export SYSCONFDIR=/etc/default
export ETCDIR=/etc/sentinel

%:
	dh $@

override_dh_auto_install:
	# make all the target directories
	mkdir -p \
		$$(pwd)/debian/$(PACKAGE_NAME)$(SENTINEL_PREFIX) \
		$$(pwd)/debian/$(PACKAGE_NAME)$(RUNTIME_PREFIX) \
		$$(pwd)/debian/$(PACKAGE_NAME)$(LOGDIR) \
		$$(pwd)/debian/$(PACKAGE_NAME)$(SYSCONFDIR)
	
	# copy all the files from the build tarball
	rsync -avr --exclude=debian $$(pwd)/ $$(pwd)/debian/$(PACKAGE_NAME)$(SENTINEL_PREFIX)/
	
	# translate Sentinel prefix and etc directories in the init script, and put it in place
	sed -e "s,/opt/sentinel/etc,$(SYSCONFDIR),g" \
			-e "s,RUNAS=root,RUNAS=sentinel,g" \
			-e "s,/opt/sentinel,$(SENTINEL_PREFIX),g" \
			$$(pwd)/etc/sentinel.init > $$(pwd)/debian/$(PACKAGE_NAME).sentinel.init \
		&& rm -f $$(pwd)/debian/$(PACKAGE_NAME)$(SENTINEL_PREFIX)/etc/sentinel.init
	
	# move etc / data / deploy directories to where they will live
	mv $$(pwd)/debian/$(PACKAGE_NAME)$(SENTINEL_PREFIX)/etc $$(pwd)/debian/$(PACKAGE_NAME)$(ETCDIR) \
		&& ln -s ../../..$(ETCDIR) $$(pwd)/debian/$(PACKAGE_NAME)$(SENTINEL_PREFIX)/etc \
		&& mv $$(pwd)/debian/$(PACKAGE_NAME)$(SENTINEL_PREFIX)/data $$(pwd)/debian/$(PACKAGE_NAME)$(RUNTIME_PREFIX)/ \
		&& ln -s ../../..$(RUNTIME_PREFIX)/data $$(pwd)/debian/$(PACKAGE_NAME)$(SENTINEL_PREFIX)/data \
		&& mv $$(pwd)/debian/$(PACKAGE_NAME)$(SENTINEL_PREFIX)/deploy $$(pwd)/debian/$(PACKAGE_NAME)$(RUNTIME_PREFIX)/ \
		&& ln -s ../../..$(RUNTIME_PREFIX)/deploy $$(pwd)/debian/$(PACKAGE_NAME)$(SENTINEL_PREFIX)/deploy \
	
	# take care of some packaging/lintian warnings
	mkdir -p $$(pwd)/debian/$(PACKAGE_NAME)/usr/share/lintian/overrides
	install -c -m 644 $$(pwd)/debian/$(PACKAGE_NAME).lintian-overrides $$(pwd)/debian/$(PACKAGE_NAME)/usr/share/lintian/overrides/$(PACKAGE_NAME)
	rm -rf $$(pwd)/debian/$(PACKAGE_NAME)$(SENTINEL_PREFIX)/COPYING
	
	# move the sentinel.conf to /etc/defaults and change the default RUNAS to sentinel
	sed -e "s,RUNAS=root,RUNAS=sentinel,g" $$(pwd)/debian/$(PACKAGE_NAME)$(ETCDIR)/sentinel.conf > $$(pwd)/debian/$(PACKAGE_NAME)$(SYSCONFDIR)/sentinel \
		&& rm -rf $$(pwd)/debian/$(PACKAGE_NAME)$(ETCDIR)/sentinel.conf
	
	# change the logging directory to /var/log/sentinel
	sed -e "s,.{karaf.data}/log,$(LOGDIR),g" -e 's,karaf.log,sentinel.log,g' $$(pwd)/etc/org.ops4j.pax.logging.cfg > $$(pwd)/debian/$(PACKAGE_NAME)$(ETCDIR)/org.ops4j.pax.logging.cfg
	
	# install the init script
	dh_installinit --package=$(PACKAGE_NAME) --name=sentinel --no-start -u"defaults 21 19"
