#!/usr/bin/make -f

# Uncomment this to turn on verbose mode.
#export DH_VERBOSE=1

MS_DIR=$(CURDIR)/debian/missing-sources
KO_FRAG=$(MS_DIR)/knockout-3.4.0/build/fragments

%:
	dh $@

override_dh_auto_build:
	mkdir $(CURDIR)/build
	mkdir -p $(CURDIR)/build/clockpicker
	mkdir -p $(CURDIR)/build/jquery/ui
	mkdir -p $(CURDIR)/build/knockout
	mkdir -p $(CURDIR)/build/knockout-jqueryui
	mkdir -p $(CURDIR)/build/leaflet
	uglifyjs -c -o $(CURDIR)/build/sammy-latest.min.js \
		$(MS_DIR)/sammy.full.js
	uglifyjs -c -o $(CURDIR)/build/jquery/jquery.jui_theme_switch.min.js \
		$(MS_DIR)/jui_theme_switch-master/jquery.jui_theme_switch.js
	uglifyjs -c -o $(CURDIR)/build/clockpicker/jquery-clockpicker.min.js \
		$(MS_DIR)/clockpicker-gh-pages/src/clockpicker.js
	cp -avT $(MS_DIR)/clockpicker-gh-pages/src/clockpicker.css \
		$(CURDIR)/build/clockpicker/jquery-clockpicker.min.css

#	Manually uglify jquery-ui - looks like images aren't used.
	for FILE in $(MS_DIR)/jquery-ui-1.11.4/ui/*.js; do \
		uglifyjs -c -o $(CURDIR)/build/jquery/ui/$$(basename $$FILE) \
			$$FILE; \
	done

#	Uglify sources from Leaflet.Geodesic
	uglifyjs -c -o $(CURDIR)/build/leaflet/Leaflet.Geodesic.min.js \
		$(MS_DIR)/Leaflet.Geodesic-master/Leaflet.Geodesic.js

#	knockout - based on $(CURDIR)/debian/missing-sources/knockout-3.4.0/Gruntfile.js lines 78-103:
#	we can't just run that because Grunt isn't in Debian yet (RFP #673727)
	echo "(function(){var DEBUG=true;" \
		| cat - $(KO_FRAG)/extern-pre.js \
			$(KO_FRAG)/amd-pre.js \
			`grep -o -e "src/.*\.js" $(KO_FRAG)/source-references.js \
				| sed -e "s;^;$(MS_DIR)/knockout-3.4.0/;"` \
			$(KO_FRAG)/amd-post.js \
			$(KO_FRAG)/extern-post.js \
		> $(CURDIR)/build/knockout/knockout-tmp.js
	echo "})();" \
		| cat $(CURDIR)/build/knockout/knockout-tmp.js - \
		| sed -e "s/##VERSION##/3.4.0/" \
		| uglifyjs -c -o $(CURDIR)/build/knockout/knockout.js -

#	punt on grunt emulation *and* uglifyjs and simply copy these
	cp $(MS_DIR)/knockout-jqueryui-2.2.2/src/*.js \
		$(CURDIR)/build/knockout-jqueryui/

override_dh_auto_clean:
	rm -rf build
	dh_auto_clean

override_dh_auto_install:
	dh_installdirs -pflightgear-phi usr/share/games/flightgear
	cp -av $(CURDIR)/Phi \
		debian/flightgear-phi/usr/share/games/flightgear/
	mkdir debian/flightgear-phi/usr/share/games/flightgear/Phi/3rdparty
	cp -av $(CURDIR)/build/* \
		debian/flightgear-phi/usr/share/games/flightgear/Phi/3rdparty/

#	Drop some extra license files.
	rm -rf debian/flightgear-phi/usr/share/games/flightgear/Phi/3rdparty/pagedown/LICENSE.txt

#	Fix permissions on mkthemes.sh.
	chmod 755 $(CURDIR)/debian/flightgear-phi/usr/share/games/flightgear/Phi/mkthemes.sh

get-orig-source:
	. debian/get-orig-source
