-- Run the following cmd to make Transmit marry iterm2 as its Terminal partner:
-- defaults write com.panic.Transmit OpenTerminalScriptPath ~/transmit-iterm-patch.applescript

on openTerminal(location, remoteHost, serverPort)
    -- Prepare sshCmd and cmd:
    set sshCmd to ""
    set cmd to "cd \"" & location & "\""

    if ((count of remoteHost) is greater than 0) then
        set sshCmd to "ssh " & remoteHost

        if (serverPort is greater than 0) then
            set sshCmd to sshCmd & " -p " & serverPort
        end if
    end if

    -- Check whether the application was open already.
    tell application "System Events"
        set wasOpen to (exists (processes where name is "iTerm")) or (exists (processes where name is "iTerm2"))
    end tell

    -- Do operations on iTerm.
    tell application "iTerm"
        activate

        -- Create window:
        if (count of windows) is 0 then
            create window with default profile
        else
            if wasOpen then
                tell first window to create tab with default profile
            end if
        end if

        -- Inside iterm2's window:
        tell first window
            if ((count of sshCmd) is greater than 0) then
                tell current session to write text sshCmd
                delay 0.5
            end if
        
        tell current session to write text cmd
        end tell
    end tell

end openTerminal