
NAME = Consistent Keyboards
VERSION = 0.5
TARBASE = Consistent_Keyboards-$(VERSION)
PKGBASE = $(TARBASE)
DMGNAME = $(NAME) $(VERSION)

CFLAGS = -Wall -DPAREN
CFLAGS = -Wall -arch i386 -arch ppc -DPACKAGE_VERSION="\"$(VERSION)\"" \
	-DPACKAGE_NAME="\"$(NAME)\""

SOURCES = Makefile daemon.c com.ljosa.consistent-keyboards.plist \
	config.plist postflight.sh license.txt \
	uninstall.sh uninstall.scpt Consistent_Keyboards.pmproj

all: daemon dist build

daemon: daemon.o
	$(CC) $(CFLAGS) -o $@ $+ -framework ApplicationServices

Uninstall\ Consistent\ Keyboards.app:
	@echo Manual step: open uninstall.scpt, then save it as application bundle Uninstall\ Consistent\ Keyboards.app
	@false

build: daemon com.ljosa.consistent-keyboards.plist config.plist postflight.sh Uninstall\ Consistent\ Keyboards.app
	if [ -a build ]; then sudo rm -rf build; fi
	mkdir -p build/Library/LaunchDaemons/
	cp com.ljosa.consistent-keyboards.plist build/Library/LaunchDaemons/
	mkdir -p build/Library/"Application Support"/Ljosa/"$(NAME)"/
	cp daemon build/Library/"Application Support"/Ljosa/"$(NAME)"/"Consistent Keyboards Daemon"
	cp config.plist build/Library/"Application Support"/Ljosa/"$(NAME)"/
	cp -rp "Uninstall Consistent Keyboards.app" build/Library/"Application Support"/Ljosa/"$(NAME)"/
	(echo %s/applet/Uninstall Consistent Keyboards/g; echo w; echo q) | ed build/Library/"Application Support"/Ljosa/"$(NAME)"/"Uninstall Consistent Keyboards.app"/Contents/Info.plist
	mv build/Library/"Application Support"/Ljosa/"$(NAME)"/"Uninstall Consistent Keyboards.app"/Contents/MacOS/{applet,"Uninstall Consistent Keyboards"}
	cp uninstall.sh build/Library/"Application Support"/Ljosa/"$(NAME)"/"Uninstall Consistent Keyboards.app"/Contents/Resources/Scripts/
	mkdir -p scripts/
	cp postflight.sh scripts/postflight
	chmod 41775 build/Library
	sudo chown -R 0:0 build
	sudo chgrp 80 build/Library

dmg: $(PKGBASE).pkg build
	mkdir -p "$(DMGNAME)"/
	cp -rp $(PKGBASE).pkg "$(DMGNAME)/$(NAME) $(VERSION).pkg"
	cp -rp build/Library/"Application Support"/Ljosa/"$(NAME)"/"Uninstall Consistent Keyboards.app" "$(DMGNAME)"/
	rm -f tmp.dmg
	hdiutil create -srcfolder "$(DMGNAME)" tmp.dmg
	rm -rf "$(DMGNAME)"/
	rm -f "$(TARBASE).dmg"
	hdiutil convert -format UDBZ -o "$(TARBASE).dmg" tmp.dmg
	rm tmp.dmg
	hdiutil internet-enable -yes "$(TARBASE).dmg"

dist: $(TARBASE).tar.gz

$(TARBASE).tar.gz: $(SOURCES)
	rm -rf $(TARBASE)
	mkdir $(TARBASE)/
	cp -rp $(SOURCES) $(TARBASE)/
	tar cvzf $(TARBASE).tar.gz $(TARBASE)
	rm -rf $(TARBASE)

distclean: clean
	rm -f *~

clean:
	rm -f daemon *.o $(TARBASE).tar.gz $(TARBASE).dmg
	rm -rf $(TARBASE) scripts "$(PKGBASE).pkg" "$(NAME) $(VERSION)"
	rm -rf "Uninstall Consistent Keyboards.app"
	if [ -a build ]; then sudo rm -rf build; fi

