#!/usr/bin/python


from urllib import urlopen
from xml.dom import minidom
import os
import sys
import time

project_index_htmlsummary_url = "https://review.tizen.org/git/"
project_index_txt_url = "https://review.tizen.org/git/?a=project_index"
igonre_projects = []

OLDMANIFEST = 'default.xml'

def changelog(new_project_list):
    if not os.path.exists(OLDMANIFEST):
        return 0, ''
    added = []
    removed = []
    dom = minidom.parse(OLDMANIFEST)
    old_project_list = []
    for oldproject in dom.getElementsByTagName('project'):
        project = oldproject.getAttribute('name')
        old_project_list.append(project)
        if project not in new_project_list:
            removed.append(project)
    for project in new_project_list:
        if project not in old_project_list:
            added.append(project)

    report = 'Checked out at ' + time.strftime('%Y-%m-%d')
    report += '\nAdded repogitories: Total %d' % len(added)
    for repo in added:
        report += '\n - %s' % repo
    report += '\n\nRemoved repogitories: Total %d' % len(removed)
    for repo in removed:
        report += '\n - %s' % repo
    return len(added) + len(removed), report

def pretty_project_element(path, name):
    ret = '  <project path="%s"' % path
    ret += ' ' * (40 - len(path))
    ret += ' name="%s"/>\n' % name
    return ret

def generate_manifest(project_list):
    manifest = """<?xml version="1.0" encoding="UTF-8"?>
<manifest>
<!--

This file was generated by %s
Authors:
  - JoonCheol Park <jooncheol@gmail.com>
  - Naruto TAKAHASHI <tnaruto@gmail.com>""" % sys.argv[0]

#    changes, report = changelog(project_list)
#    if changes > 0:
#        manifest += '\n\n' + report

    manifest += """\n\n-->
  <remote name="tizenorg" fetch="git://review.tizen.org/" />
  <default revision="master" remote="tizenorg" sync-j="4" />\n"""

    for project_path in project_list:
        # XXX merge the dir separation by first alphabet of the pkgs and apps
        # we don't have to worry about the duplication of the directories
        # and this is better to the code search and reviewing.
        local_path = project_path
        dirs = project_path.split('/')
        if len(dirs) > 2 and len(dirs[1]) == 1 and dirs[2].startswith(dirs[1]):
            local_path = project_path.replace(dirs[1] + '/', '', 1)

        manifest += pretty_project_element(local_path, project_path)
    manifest += "</manifest>"
    return manifest

class HTTPAccessFailure(Exception):
    '''Indicate the http access failed'''

def download_ignore_list():
    r = urlopen(project_index_htmlsummary_url)
    if r.code != 200:
        raise HTTPAccessFailure()
    page = r.read()
    dom = minidom.parseString(page)
    table = None
    for n in dom.getElementsByTagName('table'):
        if n.hasAttribute('class') and n.getAttribute('class') == 'project_list':
            table = n
            break
    else:
        return
    for tr in table.getElementsByTagName('tr'):
        git = None
        noage = False
        for td in tr.getElementsByTagName('td'):
            if td.hasAttribute('class') and td.getAttribute('class') == 'noage':
                noage = True
                continue
            a = td.firstChild
            if a.nodeName != 'a':
                continue
            txt = a.firstChild
            if a.getAttribute('class') == 'list' and txt:
                if txt.nodeValue[-4:] == '.git':
                    git = txt.nodeValue.strip()
        if git and noage:
            igonre_projects.append(git[:-4])



def download_project_list():
    project_list = []
    r = urlopen(project_index_txt_url)
    if r.code != 200:
        raise HTTPAccessFailure()
    for line in r.readlines():
        line = line.strip()
        if line == "":
            continue
        project_name = line.replace(".git", "")
        if project_name not in igonre_projects:
            project_list.append(project_name)
            continue
    project_list.sort()
    return project_list

if __name__ == '__main__':
    if len(sys.argv) > 1 and sys.argv[1] in ('-h', '--help'):
        print 'Usage:'
        print '  %s %s> default.xml' % (sys.argv[0], "USER")
        sys.exit(1)
    download_ignore_list()
    project_list = download_project_list()
    sys.stdout.write(generate_manifest(project_list) + '\n')

# vim: sw=4 ts=8 sts=4 et bs=2 fdm=marker fileencoding=utf8
