#!/usr/bin/env python
# encoding: utf-8


"""Search Android source code in a quicker way

A configuration file (~/agr.yaml) defines the git projects to search, e.g:

    projects:
            all: []
            tag:
                - my/git/repo1
                - my/git/repo2
"""

import os
import sys
import subprocess
import yaml


def is_android_repo():
    return os.path.isdir('.repo')


def search_pattern(projects, pattern):
    return subprocess.check_output(
            "repo forall {} -pvc 'git grep -In {}' | cat".format(
                projects, pattern),
            shell=True)


def usage():
    print("Usage:\n\t{} [tag] pattern".format(sys.argv[0]))


def main():

    if not is_android_repo():
        print("Not an Android repository")
        sys.exit(1)

    if len(sys.argv) < 2:
        usage()
        sys.exit(1)
    elif len(sys.argv) == 2:
        tag = 'all'
        pattern = sys.argv[1]
    else:
        tag = sys.argv[1]
        pattern = sys.argv[2]

    with open(os.path.join(os.path.expanduser('~'), 'agr.yaml'), 'r') as f:
        config = yaml.safe_load(f)

        projects = config.get('projects')
        if tag in projects:
            print(search_pattern(' '.join(projects[tag]), pattern))
            sys.exit(0)

    print("Tag {} not found".format(tag))
    sys.exit(1)


if __name__ == '__main__':
    main()
