#!/usr/bin/make -f

include /usr/share/dpkg/default.mk

%:
	dh $@

SHIPDIR=debian/jquery-timepicker/usr/share/javascript/jquery-timepicker

SOURCE = $(wildcard src/jquery-ui-timepicker-addon.*)
SHIP = $(patsubst %,$(SHIPDIR)/%,$(SOURCE))

VERSION_DATE=$(shell grep 'modified": ".*"' jquery-ui-timepicker-addon.json | cut -d'"' -f 4)

$(SHIPDIR)/%.js: %.js
	yui-compressor -o '.js$$:.min.js' $<

$(SHIPDIR)/%.css: %.css
	yui-compressor -o '.css$$:.min.css' $<

override_dh_clean:
	dh_clean
	if test -e debian/save; then \
		rm -f debian/save/*.min.*; \
		mv debian/save/* src/; \
		rmdir debian/save; \
	fi

override_dh_auto_build: $(SHIP)
	# Replace version and version date
	# Also apply on the dist file
	mkdir -p debian/save
	cp src/jquery-ui-timepicker-addon*.js debian/save/
	sed -i "s/@@version/$(DEB_VERSION_UPSTREAM)/g" src/jquery-ui-timepicker-addon*.js
	sed -i "s/@@timestamp/$(VERSION_DATE)/g" src/jquery-ui-timepicker-addon*.js

	cat src/docs/header.html > src/index.html
	cat src/docs/intro.html | sed "s/@@version/$(DEB_VERSION_UPSTREAM)/" | sed "s/@@timestamp/$(VERSION_DATE)/" >> src/index.html
	cat src/docs/options.html >> src/index.html
	cat src/docs/formatting.html >> src/index.html
	cat src/docs/i18n.html >> src/index.html
	cat src/docs/examples.html >> src/index.html
	cat src/docs/footer.html >> src/index.html

	# Do like Grunt would have done
	# Source: https://github.com/trentrichardson/jQuery-Timepicker-Addon/blob/397d6ed930649ea7224123d140d341e9f3ffaba6/Gruntfile.js#L55
	printf '/*! jQuery Timepicker Addon - v%s - %s\n* http://trentrichardson.com/examples/timepicker\n* Copyright (c) 2016 Trent Richardson; Licensed MIT */\n\n(function($$){\n\n' \
	$(DEB_VERSION_UPSTREAM) \
	$(VERSION_DATE) \
	> src/i18n/jquery-ui-timepicker-addon-i18n.js~
	# The ~ is for the for loop not to catch the file
	# The src/i18n/jquery-ui-timepicker-hu.js file is a UTF-8 with BOM file, the first sed removes it
	for name in src/i18n/jquery-ui-timepicker-*.js; do\
		printf '// source: %s\n' $${name} >> src/i18n/jquery-ui-timepicker-addon-i18n.js~; \
		sed '1s/^\xEF\xBB\xBF//' $${name} | sed '/(function(\$$) {/d' | sed '/(function (\$$) {/d' | sed '/})(jQuery);/d' | sed '/\$$.timepicker.setDefaults/d' >> src/i18n/jquery-ui-timepicker-addon-i18n.js~; \
		printf '\n' $${name} >> src/i18n/jquery-ui-timepicker-addon-i18n.js~; \
    done
	echo '})(jQuery);' >> src/i18n/jquery-ui-timepicker-addon-i18n.js~
	mv src/i18n/jquery-ui-timepicker-addon-i18n.js~ src/i18n/jquery-ui-timepicker-addon-i18n.js
	yui-compressor -o '.js$$:.min.js' src/i18n/jquery-ui-timepicker-addon-i18n.js
