#!/usr/bin/osascript
on run argv

    set dir to quoted form of (first item of argv)

    -- set list of shells and other misc variables
    set shells to {"bash", "zsh", "ksh", "tcsh", "sh"}
    set run_cmd to "cd " & dir & " && git status"
    set repo_name to basename(dir)

    -- set tab/session title
    set tab_title to "git: " & repo_name
    set git_terminal to null
    set git_session to null

    tell application "iTerm"
        activate

        if (count of terminals) > 0 then -- loop through all terminals
            repeat with ter in terminals
                set counter to 0
                repeat with ses in sessions of ter
                    set counter to counter + 1
                    set this_session_name to name of ses
                    if this_session_name contains tab_title then -- check for terminal with this project’s name
                        repeat with i from 1 to (length of shells) -- check the session title for the default OS X shells
                            if the this_session_name contains item i of shells then -- the session title includes the currently-running command (uses the name of the shell if no other command is running)
                                set git_terminal to ter
                                set git_session to counter
                                exit repeat
                            end if
                        end repeat
                        exit repeat
                    end if
                end repeat
            end repeat
        end if

        if git_session is null then -- if no sessions exist, create a session
            if (count of terminals) is 0 then
                set git_terminal to (make new terminal) -- create a new terminal if necessary
            else
                set git_terminal to front terminal
            end if
            tell git_terminal
                set git_session to launch session tab_title
                set the name of git_session to tab_title
                tell git_session to write text run_cmd
            end tell
        else
            -- select a currently-running session
            select git_terminal
            select session git_session of front terminal
        end if
    end tell
end run

-- adapted from http://macscripter.net/viewtopic.php?id=13286
on basename(the_path) -- Requires POSIX path
    set ASTID to AppleScript's text item delimiters
    set AppleScript's text item delimiters to "/"
    set the_path to text item -2 of the_path
    set AppleScript's text item delimiters to ASTID
    return the_path
end basename
