#! /usr/bin/make

# Makefile to convert svg, jpg and png files to PDF

SVGFILES = $(wildcard *.svg)
JPGFILES = $(wildcard *.jpg)
PNGFILES = $(wildcard *.png)
TARGETS = $(patsubst %.svg, %.pdf, $(SVGFILES)) \
          $(patsubst %.jpg, %.pdf, $(JPGFILES)) \
          $(patsubst %.png, %.pdf, $(PNGFILES))

IMAGECACHE = ../../../cache

all: prepareCache $(TARGETS)

prepareCache:
	mkdir -p $(IMAGECACHE)

%.pdf: %.png
	@echo "PNG -> $@"
	@md5=$$(md5sum $<); \
	if [ -f "$(IMAGECACHE)/$${md5}.$@" ]; then \
	  cp "$(IMAGECACHE)/$${md5}.$@" $@; \
	else \
	  gm convert $< -background white $@; \
	  cp $@ "$(IMAGECACHE)/$${md5}.$@"; \
	fi

%.pdf: %.jpg
	@echo "JPG -> $@"
	@md5=$$(md5sum $<); \
	if [ -f "$(IMAGECACHE)/$${md5}.$@" ]; then \
	  cp "$(IMAGECACHE)/$${md5}.$@" $@; \
	else \
	  gm convert $< $@; \
	  cp $@ "$(IMAGECACHE)/$${md5}.$@"; \
	fi

%.pdf: %.svg
	@echo "SVG -> $@"
	@md5=$$(md5sum $<); \
	if [ -f "$(IMAGECACHE)/$${md5}.$@" ]; then \
	  cp "$(IMAGECACHE)/$${md5}.$@" $@; \
	else \
	  rsvg-convert -f pdf $< --width 960 -o $@; \
	  cp $@ "$(IMAGECACHE)/$${md5}.$@"; \
	fi

clean:
	rm -f $(TARGETS)
	rm -rf $(IMAGECACHE)

.PHONY: all clean
