#!/usr/bin/env python

import sys
from urlparse import urlparse

def main():
    if len(sys.argv) < 3:
        print("Usage: %s <automerge-ci.conf> <automerge-ci.xml>" % sys.argv[0])
        sys.exit(1)

    remotes = {}
    repos = {}
    with open(sys.argv[1], 'r') as f:
        for line in f:
            if line.startswith('#'):
                continue
            line = line.strip()
            if not line:
                continue
            columns = line.split()

            url = urlparse(columns[1])
            remote_name = url.hostname.split('.')[-2].strip()
            fetch = "%s://%s" % (url.scheme, url.netloc)
            if not remote_name in remotes.keys():
                remotes[remote_name] = fetch

            repo_id = columns[0]
            repo_name = url.path[1:] # to remove / initial char
            repo_branch = columns[2]
            repo_remote = remote_name
            repos[repo_id] = (repo_remote, repo_name, repo_branch)

    with open(sys.argv[2], 'w') as f:
        f.write('<?xml version="1.0" encoding="UTF-8"?>\n')
        f.write('<!-- THIS FILE IS AUTOGENERATED USING automerge2repo.py -->\n')
        f.write('<manifest>\n')

        for remote_name in sorted(remotes.keys()):
            f.write('<remote fetch="%s" name="%s"/>\n' % (remotes[remote_name],
                    remote_name))

        f.write('\n')
        f.write('<default revision="master" sync-j="4"/>\n')
        f.write('\n')

        for repo_id in sorted(repos.keys()):
            f.write('<project remote="%s" name="%s" revision="%s" path="repos/%s"/>\n' % \
                    (repos[repo_id][0], repos[repo_id][1], repos[repo_id][2], repo_id))

        f.write('</manifest>\n')

if __name__ == '__main__':
    try:
        ret =  main()
    except Exception:
        ret = 1
        import traceback
        traceback.print_exc()
    sys.exit(ret)
