---
- name: clone plugin repos
  git:
    repo: 'https://github.com/{{item.repo}}.git'
    dest: '{{plugin_dir}}/{{item.mode | default("start")}}/{{item.repo | regex_replace("^.*\/(.*)$", "\1")}}'
    version: '{{item.branch | default("HEAD")}}'
  with_items: '{{plugins}}'

- name: get list of managed plugin paths
  set_fact:
    managed_plugins: >-
      {{
        managed_plugins | default([]) + [
            plugin_dir + "/" +
            item.mode | default("start") + "/" +
            item.repo | regex_replace("^.*\/(.*)$", "\1")
        ]
      }}
  with_items: '{{plugins}}'

- name: find all installed plugin directories
  find:
    paths:
      - '{{plugin_dir}}/start'
      - '{{plugin_dir}}/opt'
    file_type: directory
  register: found_plugins

- name: remove found plugins which are not in the managed list
  file:
    path: '{{item.path}}'
    state: absent
  with_items: '{{found_plugins.files}}'
  when: item.path not in managed_plugins
  loop_control:
    label: '{{item.path}}'