#!/bin/zsh

func usage() {
        echo "Usage:"
        echo "${0} (<file url>|<settings name>)"
}

PROFILE=${1}

if [[ -z ${PROFILE} ]] ; then
        usage
        exit 1
fi

osascript - `tty` ${PROFILE} <<SCRIPT
on run argv
	set theTTY to item 1 of argv
	set settingsNameOrPath to item 2 of argv
	if settingsNameOrPath starts with "file://" then
		set settingsName to my settingsNameForPath(settingsNameOrPath)
	else
		set settingsName to settingsNameOrPath
	end if
	
	if settingsName is missing value then return
	
	tell application "Terminal"
		set desiredSettings to first settings set whose name is settingsName
		if desiredSettings is missing value then return
		repeat with matchingTab in my tabForTTY(theTTY)
			set current settings of matchingTab to desiredSettings
		end repeat
	end tell
end run

on settingsNameForPath(thePath)
	if thePath ends with "SourceDirs" then return "Man Page"
	if thePath contains "SourceDirs/OmniFocus" then return "OmniFocus"
	if thePath contains "SourceDirs/OmniCurt" then return "OmniCurt"
	if thePath contains "SourceDirs/OmniPlan" then return "OmniPlan"
	if thePath contains "SourceDirs/curtclifton.net" then return "curtclifton.net"
	if thePath contains "SourceDirs" then return "Ocean"
	return missing value
end settingsNameForPath

on tabForTTY(theTTY)
	tell application "Terminal"
		repeat with aWindow in every window
			repeat with aTab in every tab of aWindow
				set currentTTY to tty of aTab
				if currentTTY is theTTY then
					return {aTab}
				end if
			end repeat
		end repeat
		return {}
	end tell
end tabForTTY
SCRIPT
