---
- name: Deploy MinIO Infrastructure on Utility VM
  hosts: utility.lab.local
  gather_facts: true
  become: false

  tasks:
    - name: Install Podman and rootless container dependencies
      become: true
      ansible.builtin.package:
        name:
          - podman
          - uidmap
          - dbus-user-session
        state: present

    - name: Create MinIO directory structures
      ansible.builtin.file:
        path: "{{ item }}"
        state: directory
        owner: "{{ admin_user }}"
        group: "{{ admin_user }}"
        mode: "0755"
      loop:
        - "/home/{{ admin_user }}/containers/minio"
        - "{{ minio_data_dir }}"

    - name: Deploy MinIO Systemd Service
      become: true
      ansible.builtin.template:
        src: "./templates/minio.service.j2"
        dest: "/etc/systemd/system/minio.service"
        mode: "0644"

    - name: Start and enable MinIO service
      become: true
      ansible.builtin.systemd_service:
        name: minio.service
        state: restarted
        enabled: true
        daemon_reload: true

    - name: Wait for MinIO API to be ready
      ansible.builtin.wait_for:
        port: 9000
        delay: 2
        timeout: 30

    - name: Install MinIO client (mc)
      become: true
      ansible.builtin.get_url:
        url: "https://dl.min.io/client/mc/release/linux-amd64/mc"
        dest: "/usr/local/bin/mc"
        mode: "0755"

    - name: Configure mc local alias
      ansible.builtin.command:
        cmd: "/usr/local/bin/mc alias set localhttp http://localhost:9000 {{ minio_root_user }} {{ minio_root_password }}"
      changed_when: false

    - name: Create 'terraform-state' bucket if it doesn't exist
      ansible.builtin.command:
        cmd: "/usr/local/bin/mc mb --ignore-existing localhttp/terraform-state"
      register: mb_result
      changed_when: "'Bucket created successfully' in mb_result.stdout"
