#!/usr/bin/env python
'''ghgrep

Usage:
   ghgrep [options] <pattern>
   ghgrep (-h | --help)
   ghgrep --version

Options:
   -h --help           Show this screen.
      --version        Show version.
   -f --fixed-strings  Interpret pattern as a fixed string instead of a regex.
   -v --invert-match   Show non-matching repos instead of those that match.
'''

# May you recognize your weaknesses and share your strengths.
# May you share freely, never taking more than you give.
# May you find love and love everyone you find.

import signal
import sys

from docopt import docopt
from envoy import run
from github3 import authorize, login, GitHub

from ghgrep import VERSION

# Stack traces are ugly; why would we want to print one on ctrl-c?
def nice_sigint(signal, frame):
   print("")
   sys.exit(0)
signal.signal(signal.SIGINT, nice_sigint)

arguments = docopt(__doc__, version='ghgrep %s' % VERSION)
pattern = arguments['<pattern>']
if arguments['--fixed-strings']:
   matcher = lambda filename: filename == pattern
else:
   from re import match
   matcher = lambda filename: bool(match(pattern, filename))

# Use a stored OAuth token so we don't have to ask for the user's password
# every time (or save the password on disk!).
token = run('git config --global ghgrep.token').std_out.strip()
if not token:
   from getpass import getpass
   user = password = ''

   while not user:
      user = raw_input('Username: ')
   while not password:
      password = getpass('Password: ')

   auth = authorize(user, password,
                    scopes=['repo'],
                    note='ghgrep',
                    note_url='https://github.com/xiongchiamiov/ghgrep')
   token = auth.token
   # We need to un-unicode token for now.
   # https://github.com/kennethreitz/envoy/issues/34
   run("git config --global ghgrep.token '%s'" % str(token))
gh = login(token=token)

for repo in gh.iter_repos():
   branch = repo.default_branch
   ref = repo.ref('heads/'+branch)
   head = ref.object.sha
   tree = repo.tree(head)
   
   for entry in tree.tree:
      if matcher(entry.path):
         if not arguments['--invert-match']:
            print(repo.name)
         break
   else: # That is, "and also":
      #    http://nedbatchelder.com/blog/201110/forelse.html
      if arguments['--invert-match']:
         print(repo.name)

