#!/usr/bin/make -f
# -*- makefile -*-
# Uncomment this to turn on verbose mode.
#export DH_VERBOSE=1

DEBVERS := $(shell dpkg-parsechangelog | sed -n -e 's/^Version: //p')
VERSION := $(shell echo '$(DEBVERS)' | sed -e 's/^[[:digit:]]*://' -e 's/[~-].*//')
MIDVERS := $(shell echo '$(VERSION)' | sed -e "s/\([[:digit:]]*\)\.\([[:digit:]]*\).*/\1-\2/;s/-01/JAN/;s/-02/FEB/;s/-03/MAR/;s/-04/APR/;s/-05/MAY/;s/-06/JUN/;s/-07/JUL/;s/-08/AUG/;s/-09/SEP/;s/-10/OCT/;s/-11/NOV/;s/-12/DEC/")
export MIDVERS
MIDASHOME=$(shell pwd)
export MIDASHOME
MID_HOME=$(MIDASHOME)/$(MIDVERS)
MID_HOME0=/usr/lib/eso-midas/$(MIDVERS)
export MID_HOME0
MID_INSTALL=$(MIDASHOME)/$(MIDVERS)/install/unix
MID_SYS=$(MIDASHOME)/$(MIDVERS)/system/unix/
MID_WORK=$(MIDASHOME)/midwork

%:
	dh  $@

override_dh_auto_configure:
	mkdir -p $(MIDVERS)
	for i in `ls -d [a-z]* | fgrep -v debian` ; do \
	  cp -alr $$i $(MIDVERS) ; \
	done
	(cd $(MID_HOME); $(MID_INSTALL)/select all)
	(cd $(MID_HOME); $(MID_INSTALL)/preinstall -a)

override_dh_auto_build:
	(cd $(MID_HOME); $(MID_INSTALL)/install1 -a CFLAGS=\"$(CFLAGS)\" )
	test -x $(MID_HOME)/monit/midasgo.exe
	(cd $(MID_HOME)/monit ; make syskeys.unix )
	$(MID_SYS)/inmidas -m $(MID_WORK) -j "@ compile.all"
	$(MID_SYS)/inmidas -m $(MID_WORK) -j "@ ascii_bin no ; bye"

override_dh_install:
	(cd $(MID_HOME) ; yes | $(MID_SYS)/cleanmidas -a)
	sed -e "s:^MIDVERS0=.*:MIDVERS0=$(MIDVERS):" \
	    -e "s:^MIDASHOME0=.*:MIDASHOME0=/usr/lib/eso-midas:" \
	    -i $(MID_HOME)/system/unix/inmidas \
	       $(MID_HOME)/system/unix/helpmidas \
	       $(MID_HOME)/system/unix/drs
	dh_install -X.mod -XCOPYING -Xsetup~ \
	           -X${MIDVERS}/test -X${MIDVERS}/install \
	           -X${MIDVERS}/system/unix/man -X${MIDVERS}/libsrc/readline

override_dh_fixperms:
	dh_fixperms
	chmod 0644 debian/eso-midas/$(MID_HOME0)/contrib/baches/*/*.fit \
	           debian/eso-midas/$(MID_HOME0)/contrib/baches/*/*.fmt \
	           debian/eso-midas/$(MID_HOME0)/contrib/baches/*/*.datorg \
	           debian/eso-midas/$(MID_HOME0)/contrib/baches/*/*.prg \
	           debian/eso-midas/$(MID_HOME0)/contrib/baches/*/*.README \
	           debian/eso-midas/$(MID_HOME0)/system/unix/makefile
	find debian/eso-midas/$(MID_HOME0)/ -name \*.sh | xargs chmod 0755 
	chmod 0755 debian/eso-midas/$(MID_HOME0)/util/bench/brun

override_dh_auto_test:
	mkdir test_tmp
	( cd test_tmp ; $(MID_SYS)/inmidas -m $(MID_WORK) -j "@ vericopy ; @@ veriall -nodisplay ; bye" )
	test -f $(MID_WORK)/veriall_*
	rm -rf test_tmp

override_dh_makeshlibs:
	# Avoid Lintian complaint: we don't have public shared libs

override_dh_clean:
	dh_clean
	rm -rf $(MIDVERS) $(MID_WORK)
