---
- name: Check installed {{ source_tool.name }} binary
  ansible.builtin.stat:
    path: "/usr/local/bin/{{ source_tool.install_name | default(source_tool.name) }}"
  register: source_tool_installed_binary

- name: Configure git safe.directory for {{ source_tool.name }}
  ansible.builtin.command:
    cmd: "git config --global --add safe.directory /usr/src/{{ source_tool.name }}"
  become_user: "{{ username }}"
  environment:
    HOME: "{{ user_home }}"
  changed_when: true

- name: Clone {{ source_tool.name }} repository
  ansible.builtin.git:
    repo: "{{ source_tool.repo }}"
    dest: "/usr/src/{{ source_tool.name }}"
    update: true
    force: true
  become_user: "{{ username }}"
  environment:
    HOME: "{{ user_home }}"
  register: source_tool_repo_state

- name: Check built {{ source_tool.name }} binary
  ansible.builtin.stat:
    path: "/usr/src/{{ source_tool.name }}/{{ source_tool.build_output_path | default(source_tool.binary_name) }}"
  register: source_tool_built_binary

- name: Build {{ source_tool.name }}
  ansible.builtin.command:
    cmd: "{{ source_tool.build_cmd }}"
    chdir: "/usr/src/{{ source_tool.name }}"
  become_user: "{{ username }}"
  environment:
    HOME: "{{ user_home }}"
    PATH: "{{ user_home }}/.cargo/bin:{{ ansible_facts.env.PATH }}"
  when:
    - source_tool_repo_state.changed or not source_tool_built_binary.stat.exists

- name: Install {{ source_tool.name }}
  ansible.builtin.copy:
    src: "/usr/src/{{ source_tool.name }}/{{ source_tool.build_output_path | default(source_tool.binary_name) }}"
    dest: "/usr/local/bin/{{ source_tool.install_name | default(source_tool.name) }}"
    remote_src: true
    owner: root
    group: root
    mode: "0755"
  become: true
  when:
    - source_tool_repo_state.changed or not source_tool_installed_binary.stat.exists
