#!/usr/bin/env python

import os
import os.path
import sys
import subprocess
import json
import collections

from lib import run

config = json.load(open(sys.argv[1]))
tree_name = sys.argv[2]

repo_path = config['trees'][tree_name]['files_path']

stdout = run('git ls-files', shell=True, cwd=repo_path)
lines = stdout.split('\n')

files = []
js = []
idl = []

dirs = collections.OrderedDict()

for line in lines:
    path = line.strip()
    if not path:
        continue

    fullpath = os.path.join(repo_path, path)

    elts = path.split('/')
    for i in range(len(elts)):
        sub = '/'.join(elts[:i])
        if sub and sub not in dirs:
            dirs[sub] = True

    files.append(path + '\n')

    (_, ext) = os.path.splitext(path)

    if ext in ['.js', '.jsm', '.xml', '.xul', '.inc']:
        js.append(path + '\n')

index_path = config['trees'][tree_name]['index_path']
open(os.path.join(index_path, 'repo-files'), 'w').writelines(files)
open(os.path.join(index_path, 'repo-dirs'), 'w').writelines([ d + '\n' for d in dirs ])
open(os.path.join(index_path, 'js-files'), 'w').writelines(js)
open(os.path.join(index_path, 'idl-files'), 'w').writelines(idl)
