#!/bin/zsh
# UISpec CLI Runner
# By Blake Watters <blake@twotoasters.com>
# Base code taken from: http://stackoverflow.com/questions/1514302/build-and-run-an-xcode-project-via-applescript

BUILD_PATH=$(dirname $0)

while [[ -z $BUILD_FILE && $BUILD_PATH != "/" ]]; do
    BUILD_FILE=$(find $BUILD_PATH -name '*.xcodeproj' -maxdepth 1)
    BUILD_PATH=$(dirname $BUILD_PATH)
done

if [[ -z $BUILD_FILE ]]; then
    echo "Couldn't find an xcode project file in directory"
    exit 1
fi

# Applescript likes's : instead of / (because it's insane)
BUILD_FILE=${BUILD_FILE//\//:}

# Find the latest Simulator SDK
SIMULATOR_SDKS=( /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/*.sdk )

SIMULATOR_SDK=${SIMULATOR_SDKS[-1]} 
SIMULATOR_SDK_STRING=$(basename ${(L)SIMULATOR_SDK%.[a-z]*})

if [[ -z $SIMULATOR_SDK ]]; then
    echo "Couldn't find a simulator SDK"
    exit 1
fi

# Use the first arg as the spec to run...
UISPEC_RUN_SPEC=$1

osascript <<SCRIPT
on setEnvironmentVariable(variableName, variableValue)
	
	tell application "Xcode"		
		tell active project document			
			set executableName to name of executable of active target as string			
			tell executable executableName
				
				-- Check to see if the fallback path already exists				
				set hasVariable to false as boolean
				
				repeat with environmentVariable in environment variables					
					if name of environmentVariable is equal to variableName then						
						-- Overwrite any value						
						set value of environmentVariable to variableValue						
						set active of environmentVariable to yes						
						set hasVariable to true as boolean						
						exit repeat						
					end if					
				end repeat
				
				-- Since the fallback path doesn't exist yet, create it				
				if not hasVariable then					
					make new environment variable with properties {name:variableName, value:variableValue, active:yes}					
				end if				
			end tell -- executable			
		end tell -- active project document		
	end tell -- Xcode
	
end setEnvironmentVariable

application "iPhone Simulator" quit
application "iPhone Simulator" activate

tell application "Xcode"
    open "$BUILD_FILE"
    set targetProject to project of active project document
		my setEnvironmentVariable("UISPEC_RUN_SPEC", "$UISPEC_RUN_SPEC")
		
    tell targetProject
        set active build configuration type to build configuration type "Debug"
        set active SDK to "$SIMULATOR_SDK_STRING"
				set the active target to the target named "UISpec"
        set value of build setting "SDKROOT" of build configuration "Debug" of active target to "$SIMULATOR_SDK"
				
				build targetProject
				launch targetProject
    end tell
end tell
SCRIPT