#!/usr/bin/env python
#
# Copyright (C) 2011 Fog Creek Software
# Copyright (C) 2009 Steve Borho <steve@borho.org> 
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import os
import sys
import subprocess

def find_root(path=None):
    p = path or os.getcwd()
    while not os.path.isdir(os.path.join(p, ".hg")):
        oldp = p
        p = os.path.dirname(p)
        if p == oldp:
            return None
        if not os.access(p, os.R_OK):
            return None
    return p

# When TortoiseHg is started, its current directory will be the directory
# inside the app bundle where thg.py is located, not the directory from
# which the user invoked thg.  Therefore, provide the correct starting
# repository on the command line if the user hasn't specified one.
argv = sys.argv[1:]
if '-R' not in argv and '--repository' not in argv:
    path = find_root(os.getcwd())
    if path:
        argv = ['-R', path] + argv
subprocess.call(['open', '-a', 'TortoiseHg.app', '--args'] + argv)
