#!/usr/bin/make -f
include /usr/share/dpkg/pkg-info.mk

BUILDS := builds/moment-timezone-with-data.js \
          builds/moment-timezone-with-data-1970-2030.js \
          builds/moment-timezone-with-data-2012-2022.js \
          builds/moment-timezone-with-data-10-year-range.js

TARGETS := $(patsubst %.js,%.min.js,$(BUILDS)) \
           moment-timezone.min.js \
           moment-timezone-utils.min.js

# If the Debian version ends in a +tzver, regenerate the time zone data files
# from the installed tzdata package.
TZVER := $(shell echo '$(DEB_VERSION)' | \
    sed -n 's/^.*+\([0-9]\{4\}[a-z]\)$$/\1/p' )


ifeq (,$(TZVER))
$(error Missing tzdata code in Debian version $(TZVER))
endif

all: binary
%:
	dh $@

execute_before_dh_auto_configure:
	# Fail the build if the tzdata package does not match TZVER.
	grep -q '^# version $(TZVER)$$' /usr/share/zoneinfo/tzdata.zi

override_dh_auto_build: $(TARGETS)

execute_before_dh_auto_test: tests/zones/zulu.js

execute_after_dh_auto_clean:
	echo $(TZVER) $(DEB_VERSION)
	rm -rf temp/


%/latest.json: %/$(TZVER).json
	cp $< $@

temp/download/$(TZVER)/NEWS:
	mkdir -p temp/download/$(TZVER)
	ln -s /usr/share/zoneinfo/*.tab temp/download/$(TZVER)/
	zcat /usr/share/doc/tzdata/NEWS.gz > temp/download/$(TZVER)/NEWS

data/meta/$(TZVER).json: temp/download/$(TZVER)/NEWS
	grunt data-meta:$(TZVER)

data/unpacked/$(TZVER).json: data/meta/$(TZVER).json
	mkdir -p temp/zic/$(TZVER) temp/zdump/$(TZVER)
	cp -RL /usr/share/zoneinfo/posix/* temp/zic/$(TZVER)/
	# Not supported.
	rm -f temp/zic/$(TZVER)/Factory
	grunt data-zdump:$(TZVER)
	grunt data-collect:$(TZVER)
	grunt data-dedupe:$(TZVER)

data/packed/$(TZVER).json: data/unpacked/$(TZVER).json
	grunt data-pack:$(TZVER)

$(BUILDS): data/packed/latest.json moment-timezone.js
	grunt build

builds/moment-timezone.min.js: moment-timezone.js
	uglifyjs $< -o $@

%.min.js: %.js
	uglifyjs $< -o $@

tests/zones/%.js: data/packed/latest.json temp/collect/latest.json
	grunt data-tests
