---
# Copyright (c) 2022, Gregory Furlong <gnfzdz@fzdz.io>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later

- name: "Match targeted filesystem by label"
  block:
  - name: Match '{{ btrfs_subvolume_target_label }}' filesystem by label
    community.general.btrfs_subvolume:
      automount: Yes
      name: "/match_label"
      filesystem_label: "{{ btrfs_subvolume_target_label }}"
      state: "present"
    register: result

  - name: Validate the '{{ btrfs_subvolume_target_label }}' filesystem was chosen
    ansible.builtin.assert:
      that:
        - result.filesystem.label == btrfs_subvolume_target_label

- name: "Match targeted filesystem by uuid"
  block:
  - name: Match '{{ btrfs_subvolume_target_label }}' filesystem by uuid
    community.general.btrfs_subvolume:
      automount: Yes
      name: "/match_uuid"
      filesystem_uuid: "{{ result.filesystem.uuid }}"
      state: "present"
    register: result

  - name: Validate the '{{ btrfs_subvolume_target_label }}' filesystem was chosen
    ansible.builtin.assert:
      that:
        - result.filesystem.label == btrfs_subvolume_target_label

- name: "Match targeted filesystem by devices"
  block:
  - name: Match '{{ btrfs_subvolume_target_label }}' filesystem by device
    community.general.btrfs_subvolume:
      automount: Yes
      name: "/match_device"
      filesystem_device: "{{ result.filesystem.devices | first }}"
      state: "present"
    register: result

  - name: Validate the '{{ btrfs_subvolume_target_label }}' filesystem was chosen
    ansible.builtin.assert:
      that:
        - result.filesystem.label == btrfs_subvolume_target_label

- name: "Match only mounted filesystem"
  block:
  - name: "Mount filesystem '{{ btrfs_subvolume_target_label }}'"
    ansible.posix.mount:
      src: "{{ result.filesystem.devices | first }}"
      path: /mnt
      opts: "subvolid={{ 5 }}"
      fstype: btrfs
      state: mounted

  - name: Print current status
    community.general.btrfs_info:

  - name: Match '{{ btrfs_subvolume_target_label }}' filesystem when only mount
    community.general.btrfs_subvolume:
      automount: Yes
      name: "/match_only_mounted"
      state: "present"
    register: result

  - name: "Unmount filesystem '{{ btrfs_subvolume_target_label }}'"
    ansible.posix.mount:
      path: /mnt
      state: absent

  - name: Validate the '{{ btrfs_subvolume_target_label }}' filesystem was chosen
    ansible.builtin.assert:
      that:
        - result.filesystem.label == btrfs_subvolume_target_label
  when: False  # TODO don't attempt this if the host already has a pre-existing btrfs filesystem
