# Copyright (c) 2018, Red Hat, Inc.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.
#
#
---
#------------------------------------------------------------------------------
# Setup an LVM VG that will be used by cinderlib's functional tests
#------------------------------------------------------------------------------
- hosts: all
  vars:
    cldir: .
    vg: cinder-volumes
    ansible_become: yes
  tasks:
      - name: Install LVM package
        package:
          name: lvm2
          state: present

      - name: Create LVM backing file
        command: "truncate -s 10G {{vg}}"
        args:
            creates: "{{cldir}}/{{vg}}"

      - name: Check if VG already exists
        shell: "losetup -l | awk '/{{vg}}/ {print $1}'"
        changed_when: false
        register: existing_loop_device

      - name: "Create loopback device {{vg}}"
        command: "losetup --show -f {{cldir}}/{{vg}}"
        register: new_loop_device
        when: existing_loop_device.stdout == ''
      # Workaround because Ansible destroys registers when skipped
      - set_fact: loop_device="{{ new_loop_device.stdout if new_loop_device.changed else existing_loop_device.stdout }}"

      - name: "Create VG {{vg}}"
        shell: "vgcreate {{vg}} {{loop_device}} && touch {{cldir}}/lvm.vgcreate"
        args:
            creates: "{{cldir}}/lvm.vgcreate"

      - command: "vgscan --cache"
        changed_when: false

      - name: Install iSCSI packages
        package:
          name:
            - iscsi-initiator-utils
            - targetcli
          state: present

      - name: Create initiator name
        shell: echo InitiatorName=`iscsi-iname` > /etc/iscsi/initiatorname.iscsi
        args:
            creates: /etc/iscsi/initiatorname.iscsi

      - name: Start iSCSI initiator
        service:
            name: iscsid
            state: started
