# Créer son module pour Odoo

## Créer un script d'installation automatisée

Ce script python va permettre d'automatiser l'installation des modules de base

??? note "init.py"
    ```
    import odoorpc
    import subprocess
    import os
    import shutil

    # Configuration
    ODOO_URL = 'http://localhost:10014'
    ODOO_DB = 'odoo'
    ODOO_USERNAME = 'garagenum@gmail.com'
    ODOO_PASSWORD = 'bellinux'

    # Applications to install
    APPS_TO_INSTALL = [
        'account',
        'sale_management',
        'purchase',
        'hr',
        'contacts',
        'hr_expense',
        'project',
        'stock',
        'membership',
        'website',
        'mass_mailing',
        'partner_autocomplete',
        'hr_recruitment',
        'survey',
        'board',
        'mass_mailing_sms',
        'note',
        'website_forum',
        'hr_skills',
        'hr_holidays',
        'website_hr_recruitment',
        'hr_contract',
        'website_slides',
        'board',
        'base_automation',
        'delivery',
    ]

    MODULES_TO_INSTALL = [
        {'url': 'https://github.com/odoomates/odooapps', 
        'apps': [
            {'name': 'accounting_pdf_reports'},
            {'name': 'om_account_asset'},
            {'name': 'om_account_bank_statement_import'},
            {'name': 'om_account_budget'},
            {'name': 'om_fiscal_year'},
            {'name': 'om_recurring_payments'},
            {'name': 'om_account_daily_reports'},
            {'name': 'om_account_followup'},
            {'name': 'om_account_accountant', 'dir': 'om_account_accountant'}
        ]},
    ]

    def connect_odoo():
        # Connect to the Odoo server
        odoo = odoorpc.ODOO('localhost', port=10014)
        odoo.login(ODOO_DB, ODOO_USERNAME, ODOO_PASSWORD)
        return odoo


    def install_app(odoo, odoo_app):
        # Check if each module is installed or not
        print(f"Checking {odoo_app} installation...")
        module_id = odoo.env['ir.module.module'].search([('name', '=', odoo_app)])
        if module_id:
            module = odoo.env['ir.module.module'].browse(module_id)[0]
            if module.state not in ['installed', 'to upgrade']:
                module.button_immediate_install()
                print(f"Module {odoo_app} has been installed.")
            else:
                print(f"Module {odoo_app} is already installed.")
        else:
            print(f"Module {odoo_app} not found.")

    def install_apps(odoo):
        for odoo_app in APPS_TO_INSTALL:
            install_app(odoo, odoo_app)

    def dl_modules(group):
        repo_url = group['url'].rstrip('/')
        addons_path = "addons"
        os.makedirs(addons_path, exist_ok=True)
        git_dir_path = os.path.join(addons_path, '.git')

        sparse_checkout_lines = []
        search_git = True
        for app in group['apps']:
            app_dir = app['dir'] if 'dir' in app else app['name']
            app_path = os.path.join(addons_path, app_dir)
            backup_git_path = os.path.join(app_path, ".git_backup")

            sparse_checkout_lines.append(f"{app_dir}\n")
            subprocess.run(["mkdir", "-p", app_path])
            if search_git and os.path.isdir(backup_git_path):
                subprocess.run(["mkdir", "-p", git_dir_path])
                shutil.copytree(backup_git_path, git_dir_path, dirs_exist_ok=True)
                search_git = False
            
        for app in group['apps']:
            app_dir = app['dir'] if 'dir' in app else app['name']
            app_path = os.path.join(addons_path, app_dir)
            backup_git_path = os.path.join(app_path, ".git_backup")
            shutil.rmtree(backup_git_path)
            subprocess.run(["mkdir", "-p", backup_git_path])
            shutil.copytree(git_dir_path, backup_git_path, dirs_exist_ok=True)
            print(f"backup for app {app['name']}")
            

        sparse_checkout_file_path = os.path.join(git_dir_path, 'info', 'sparse-checkout')
        branch_name = "16.0"

        if not os.path.isdir(git_dir_path):
            subprocess.run(["git", "init"], cwd=addons_path)
            subprocess.run(["git", "remote", "add", "origin", repo_url], cwd=addons_path)
            subprocess.run(["git", "config", "core.sparseCheckout", "true"], cwd=addons_path, check=True)

        with open(sparse_checkout_file_path, "w") as sparse_checkout_file:
            sparse_checkout_file.writelines(sparse_checkout_lines)

        subprocess.run(["git", "pull", "origin", branch_name], cwd=addons_path, check=True)
        shutil.rmtree(git_dir_path)

        print(f"Modules {', '.join(app['name'] for app in group['apps'])} has been downloaded")

    def update_module_list(odoo):
        ModuleUpdate = odoo.env['base.module.update']
        module_update_id = ModuleUpdate.create({})
        module_update = ModuleUpdate.browse(module_update_id)
        module_update.update_module()
        updated_modules = module_update.updated
        added_modules = module_update.added
        print(f"Updated modules: {updated_modules}, Added modules: {added_modules}")


    def install_modules(odoo):
        for group in MODULES_TO_INSTALL:
            dl_modules(group)
        update_module_list(odoo)
        for group in MODULES_TO_INSTALL:
            for app in group['apps']:
            install_app(odoo, app['name'])

    def main():
        odoo = connect_odoo()
        install_apps(odoo)
        install_modules(odoo)
        print("Script execution finished!")

    main()
    ```