# This Makefile builds the XCode project in this directory to
# produce a skeleton application in build/$(CONFIG).  It then
# builds the Scheme application in this directory and inserts
# the resulting binary into the application to complete it.
# It also creates a shell script "runapp" which, when run from
# a terminal, will start the application attached to a TTY.
# At startup, runapp switches to the directory it's located in.

# Targets: 
#   compile:   The default.  Generate an application and binary as above.
#              For convenience, a link to the application is created in 
#              the current directory.
#   interpret: Configures the application to start csi when run.
#              You'll need to use runapp so a TTY is attached.
#              This csi instance doesn't load any code by default,
#              but has access to bundle resources.  You can load your
#              code and start the app with objc:nsapplication-main.

# APPNAME: Application name.   Also used as the final bundled
#          executable name.
# CONFIG:  XCode build configuration.
APPNAME=Currency\ Converter
CONFIG=Debug

# This section and the user build section at the end of this
# file may be changed according to your compilation needs.  
# NB: The final output file should be stored as BINARY, since
#     BINARY will be copied into the application bundle.
# 
# BINARY:  csc output file in this directory.
# SOURCES: Sources compiled with csc to form BINARY.
BINARY=converter
SOURCES=converter.scm

# CSI: Path to csi binary for target 'interpret'.
CSI=/usr/local/bin/csi
# BINARGS: Arguments to pass the binary when invoked via runapp.
BINARGS=

# Some internal settings.
# APPDIR: The built XCode application.
# BINDIR: The binary directory inside this application.
# BUNDLED_BINARY: Final executable name (Project->Edit Active Target->
#                 Properties->Executable).
APP=$(APPNAME).app
APPDIR=build/$(CONFIG)/$(APP)
BINDIR=$(APPDIR)/Contents/MacOS
BUNDLED_BINARY=$(BINDIR)/$(APPNAME)

all: compile
.PHONY: xcode interpret

xcode:
	xcodebuild -configuration $(CONFIG)

$(BINDIR):
	mkdir -p $(BINDIR)

compile: xcode $(BINDIR) $(BINARY) runapp linkapp
	rm -f $(BUNDLED_BINARY)
	cp -p $(BINARY) $(BUNDLED_BINARY)

interpret: xcode $(BINDIR) runapp
	rm -f $(BUNDLED_BINARY)
	ln -s $(CSI) $(BUNDLED_BINARY)

# We can't just link this---we must exec the actual path
# for the application icon and main menu to appear.
# IAM is expanded at runtime to find our location.
IAM="$${0%/*}"
runapp:
	rm -f ./runapp
	echo -e '#!/bin/sh\ncd $(IAM) && exec $(IAM)/$(BUNDLED_BINARY) $(ARGS) $$*' > ./runapp
	chmod +x ./runapp

linkapp:
	rm -f $(APP)
	ln -s $(APPDIR) $(APP)

clean:
	rm -rf build
	rm -f $(APP)
	rm -f $(BINARY)
	rm -f ./runapp
	

# User build section

$(BINARY): $(SOURCES)
	csc -O2 -X objc -d1 -o $(BINARY) $(SOURCES)

