---
- name: Define bhyve guest service definitions
  file:
    path: '{{ s6_etc_dir }}/service/bhyve-{{ item.0.name }}{{ item.1 }}'
    state: directory
    owner: root
    group: wheel
    mode: 0755
  loop_control:
    label: 'bhyve-{{ item.0.name }}{{ item.1 }}'
  with_nested:
    - '{{ bhyve_guests }}'
    - '{{ bhyve_dirs }}'
  notify:
    - Reload s6-rc

- name: Instantiating service templates
  template:
    dest: '{{ s6_etc_dir }}/service/bhyve-{{ item.0.name }}{{ item.1.name }}'
    src: 'bhyve{{ item.1.name }}.j2'
    owner: root
    group: wheel
    mode: '{{ item.1.mode }}'
  loop_control:
    label: 'bhyve-{{ item.0.name }}{{ item.1.name }}'
  with_nested:
    - '{{ bhyve_guests }}'
    - '{{ bhyve_templates }}'
  notify:
    - Reload s6-rc

- name: Flush handlers
  meta: flush_handlers

- name: Start enabled bhyve guests
  command: >
    fdmove -c 2 1 s6-rc -l {{ s6_live_dir }} -v 2 -u change bhyve-{{ item.name }}
  register: change
  when: item.enabled | default
  changed_when: change.stdout | length > 0
  loop_control:
    label: 'bhyve-{{ item.name }}'
  with_items: '{{ bhyve_guests }}'

- name: Create bhyve service
  file:
    path: '{{ item }}'
    state: directory
    owner: root
    group: wheel
    mode: 0755
  notify:
    - Reload s6-rc
  with_items:
    - '{{ s6_etc_dir }}/service/bhyve'
    - '{{ s6_etc_dir }}/service/bhyve-disabled'
    - '{{ s6_etc_dir }}/service/bhyve-enabled'

- name: Declare bhyve service as bundle
  copy:
    dest: '{{ s6_etc_dir }}/service/{{ item }}/type'
    content: bundle
    owner: root
    group: wheel
    mode: 0444
  notify:
    - Reload s6-rc
  with_items:
    - bhyve
    - bhyve-enabled
    - bhyve-disabled

- name: Define bhyve service bundles
  template:
    dest: '{{ s6_etc_dir }}/service/{{ item }}/contents'
    src: '{{ item }}-contents.j2'
    owner: root
    group: wheel
    mode: 0444
  notify:
    - Reload s6-rc
  with_items:
    - bhyve
    - bhyve-enabled
    - bhyve-disabled

- name: Flush handlers (again)
  meta: flush_handlers

- name: Stop disabled bhyve guests
  command: >
    fdmove -c 2 1 s6-rc -l {{ s6_live_dir }} -v 2 -d change bhyve-disabled
  register: change
  changed_when: change.stdout | length > 0

- name: Autostart enabled bhyve guests
  lineinfile:
    path: '{{ s6_etc_dir }}/service/enabled/contents'
    regexp: '^bhyve-enabled$'
    line: 'bhyve-enabled'
  notify:
    - Reload s6-rc