- name: create groups
  group:
    name: "{{ item.group }}"
    gid: "{{ item.gid }}"
  loop:
    - { group: local,       gid: 1000 }
    - { group: mirror,      gid: 1001 }
    - { group: push,        gid: 1002 }
    - { group: syscom,      gid: 10001 }
    - { group: csc-mirror,  gid: 10014 }

- name: create users
  # syscom and csc-mirror homes are on /users
  # can login to every user using password
  user:
    uid: "{{ item.uid }}"
    name: "{{ item.user }}"
    group: "{{ item.user }}"
    shell: "{{ item.shell }}"
    create_home: "{{ item.home }}"
    password: "{{ 'password' | password_hash('sha512') }}"
    update_password: on_create
  loop:
    - { user: local,     uid: 1000,  shell: /bin/bash, home: yes }
    - { user: mirror,     uid: 1001,  shell: /bin/bash, home: yes }
    - { user: push,       uid: 1002,  shell: /bin/sh,   home: no }
    - { user: syscom,     uid: 10001, shell: /bin/bash, home: no }
    - { user: csc-mirror, uid: 10014, shell: /bin/bash, home: no }

- name: add mirror to push group
  user:
    name: mirror
    groups: push
    append: yes

- name: create /mirror
  file:
    path: /mirror
    state: directory
    owner: root
    group: root
    mode: "0755"

- name: create /mirror/merlin
  file:
    path: /mirror/merlin
    state: directory
    owner: root
    group: root
    mode: "0755"

- name: create /mirror/root
  file:
    path: /mirror/root
    state: directory
    owner: mirror
    group: syscom
    mode: "0775"

- name: create zfs mountpoint
# only .cscmirror1 is owned by mirror
# .cscmirror(2|3) are owned by root
  file:
    path: /mirror/root/.cscmirror
    state: directory
    owner: mirror
    group: mirror
    mode: "0755"

- name: install zfs
  apt:
    name: zfsutils-linux
    state: present
    update_cache: yes

# create the var using
# vars:
#   disks:
#     - /dev/vdc 
#     - /dev/vdd 
#     - /dev/vde 
#     - /dev/vdf
#   disk_arg: "{{ disks | join(' ') }}"

# hardcoded for now
# may be better to use the /dev/disk/by-id/... instead
- name: disks to be used for zpool
  set_fact:
    disks:
      - /dev/vdc 
      - /dev/vdd 
      - /dev/vde 
      - /dev/vdf

- name: join disk pathes onto one line
  set_fact:
    disk_arg: "{{ disks | join(' ') }}"

- name: zpool exists
  command: "zpool status cscmirror"
  changed_when: false
  ignore_errors: true
  register: zpool_exists

- name: create and mount zpool
  command: >
    zpool create 
    -m /mirror/root/.cscmirror 
    cscmirror 
    raidz2 
    {{ disk_arg }}
  when: zpool_exists.rc != 0
