---
- name: Test host to host tunnel with generated PSK
  hosts: all
  tags:
    - tests::no_serialization
  vars_files:
    - './vars/main.yml'
  vars:
    __vpn_num_hosts: 2
    # test to set true to manage selinux only
    vpn_manage_selinux: true
  tasks:
    - name: Set up test environment
      include_tasks: tasks/setup_test.yml

    - name: Add extra options to check
      set_fact:
        vpn_connections: "{{ vpn_connections | map('combine', fixed_item) | list }}"
      vars:
        fixed_item:
          auto: start

    - name: Use vpn role
      include_role:
        name: linux-system-roles.vpn
        public: true

    - name: Assert file existence
      include_tasks: tasks/assert_conf_secrets_files_exist.yml

    - name: Reset success flag
      set_fact:
        __vpn_success: true

    - name: Get and store conf files
      slurp:
        src: "/etc/ipsec.d/{{ inventory_hostname }}-to-{{ item }}.conf"
      register: __vpn_register_conf
      loop: "{{ groups['testing'] }}"

    - name: Check that conf file contains correct information
      set_fact:
        __vpn_success: false
      when: >-
        item.content | b64decode is not
        search('left=' + __vpn_main_hostname) or
        item.content | b64decode is not
        search('leftid=@' + __vpn_main_hostname) or
        item.content | b64decode is not
        search('right=host0' + (idx + 1) | string + '.local') or
        item.content | b64decode is not
        search('rightid=@host0' + (idx + 1) | string + '.local') or
        item.content | b64decode is not
        search('ikev2=insist') or
        item.content | b64decode is not
        search('authby=secret') or
        item.content | b64decode is not
        search('auto=start')
      loop: '{{ __vpn_register_conf.results }}'
      loop_control:
        index_var: idx

    - name: Assert success for conf files
      assert:
        that: __vpn_success | d(false)
        msg: Found errors in .conf files

    - name: Get and store secrets files
      slurp:
        src: "/etc/ipsec.d/{{ inventory_hostname }}-to-{{ item }}.secrets"
      register: __vpn_register_secrets
      loop: "{{ groups['testing'] }}"

    - name: Check that secrets file contains correct information
      set_fact:
        __vpn_success: false
      when: >-
        item.content | b64decode |
        regex_search('^@' + __vpn_main_hostname + ' @host0' +
        (idx + 1) | string + '\.local : PSK .*',
        multiline=True) | d() | length == 0
      loop: '{{ __vpn_register_secrets.results }}'
      loop_control:
        index_var: idx

    - name: Assert success for secrets files
      assert:
        that: __vpn_success | d(false)
        msg: Found errors in .conf files

    - name: Check the firewall and the selinux port status
      include_tasks: tasks/check_firewall_selinux.yml

    - name: Cleanup
      include_tasks: tasks/cleanup.yml
      tags:
        - tests::cleanup
