---
- name: Odoo Update Modules
  hosts: optovia_servers
  become: yes
  gather_facts: no

  # Usage: ansible-playbook -i ansible/inventory/production/hosts.yml ansible/playbooks/odoo-update-modules.yml -e "modules=products"

  pre_tasks:
    - name: Validate modules parameter
      assert:
        that:
          - modules is defined
          - modules != ""
        fail_msg: "Parameter 'modules' required! Use: -e 'modules=products'"

  tasks:
    - name: Get Odoo container ID
      shell: docker ps --filter "name={{ odoo_container }}" --format "{%raw%}{{.ID}}{%endraw%}" | head -1
      register: container_id

    - name: Update Odoo modules
      shell: |
        docker exec {{ container_id.stdout }} python3 -c "
        import os, subprocess
        from infisical_sdk import InfisicalSDKClient
        client = InfisicalSDKClient(host=os.environ['INFISICAL_API_URL'])
        client.auth.universal_auth.login(client_id=os.environ['INFISICAL_CLIENT_ID'], client_secret=os.environ['INFISICAL_CLIENT_SECRET'])
        for path in ['/odoo', '/shared']:
            try:
                secrets = client.secrets.list_secrets(environment_slug=os.environ.get('INFISICAL_ENV', 'prod'), secret_path=path, project_id=os.environ['INFISICAL_PROJECT_ID'], expand_secret_references=True, view_secret_value=True)
                for s in secrets.secrets: os.environ[s.secretKey] = s.secretValue
            except: pass
        result = subprocess.run([
            'odoo',
            '--database=' + os.environ['ODOO_DB_NAME'],
            '--db_host=' + os.environ['ODOO_DB_HOST'],
            '--db_port=' + os.environ['ODOO_DB_PORT'],
            '--db_user=' + os.environ['ODOO_DB_USER'],
            '--db_password=' + os.environ['ODOO_DB_PASSWORD'],
            '-u', '{{ modules }}',
            '--stop-after-init',
            '--no-http'
        ], capture_output=True, text=True)
        print(result.stdout)
        print(result.stderr, file=__import__('sys').stderr)
        __import__('sys').exit(result.returncode)
        "
      register: update_result

    - name: Display update output
      debug:
        var: update_result
        verbosity: 0

    - name: Restart Odoo container
      shell: docker restart {{ container_id.stdout }}
