#!/usr/bin/env python3
import os
import subprocess
import tempfile
import time

from setuptools_odoo import manifest

SERIES = [
    # branch, suffix, enterprise
    ('master', '14', True),
    ('13.0', '13', True),
    ('12.0', '12', True),
    #('11.0', '11', True),
    #('10.0', '10', True),
    #('9.0', '9', True),
    #('8.0', '8', False),
    #('7.0', '7', False),
]


def _list_addons(addons_dir, add_base):
    if add_base:
        yield 'base'
    for addon_name in os.listdir(addons_dir):
        addon_dir = os.path.join(addons_dir, addon_name)
        if manifest.get_manifest_path(addon_dir):
            yield addon_name


def _write_addons_list(addons_dir, suffix, add_base):
    with open('addons-%s.txt' % suffix, 'w') as f:
        print("# generated on", time.asctime(), file=f)
        for addon_name in sorted(_list_addons(addons_dir, add_base)):
            print(addon_name, file=f)


def check_call(cmd):
    print(" ".join(cmd))
    subprocess.check_call(cmd)


def main():
    for branch, suffix, enterprise in SERIES:
        with tempfile.TemporaryDirectory() as tmpdir:
            check_call([
                'git', 'clone',
                '--branch', branch,
                'https://github.com/odoo/odoo',
                tmpdir,
            ])
            addons_dir = os.path.join(tmpdir, 'addons')
            _write_addons_list(addons_dir, suffix + 'c', add_base=True)
        if enterprise:
            with tempfile.TemporaryDirectory() as tmpdir:
                check_call([
                    'git', 'clone',
                    '--branch', branch,
                    'git@github.com:odoo/enterprise',
                    tmpdir,
                ])
                addons_dir = tmpdir
                _write_addons_list(addons_dir, suffix + 'e', add_base=False)


main()
