---
- hosts: localhost
  gather_facts: yes
  vars:
    artifacts: "{{ lookup('env', 'TEST_ARTIFACTS')|default('./artifacts', true) }}"
    subjects: "{{ lookup('env', 'TEST_SUBJECTS')}}"
  tags:
    - atomic

  tasks:
    - name: Prepare an SSH config
      set_fact:
        ssh_config: |
          Host vmcheck
            User {{ansible_ssh_user}}
            Port {{ansible_ssh_port}}
            HostName {{ansible_ssh_host}}
            IdentityFile {{ansible_ssh_private_key_file}}
            UserKnownHostsFile /dev/null
            StrictHostKeyChecking no

    - name: Add executor host
      add_host:
        name: executor
        ansible_connection: local
        ansible_ssh_host: 127.0.0.1
        ansible_ssh_connection: local

    # XXX: move to standard-test-roles, e.g. standard-test-get-source
    - name: Extract and run tests
      delegate_to: executor
      block:
      - name: Gather facts
        setup:
        delegate_facts: True

      - name: Install requirements
        package: name={{item}} state=present
        with_items:
         - fedpkg

      # The dist doesn't actually matter here, it's just so we don't barf on
      # private branches.
      - name: Download and extract sources
        command: fedpkg --dist=master prep
        args:
          chdir: "{{playbook_dir}}/.."

      - name: Get source directory from environment
        shell: rpm -q --specfile {{playbook_dir}}/../rpm-ostree.spec
               --qf '{{playbook_dir}}/../%{NAME}-%{VERSION}\n' | head -n1
        register: srcdir_query

      - set_fact:
          srcdir: "{{srcdir_query.stdout}}"

      - name: Write out SSH config
        copy:
          content: "{{ssh_config}}"
          dest: "{{srcdir}}/ssh-config"

      - set_fact:
          vmssh: ssh -F {{srcdir}}/ssh-config vmcheck

      - name: Get rpm-ostree status
        command: "{{vmssh}} rpm-ostree status --json"

      - name: Run vmcheck
        block:
        - name: Start test
          command: tests/vmcheck/multitest.py vmcheck
          # XXX: consider making vmcheck become an installed test
          environment:
            VMTESTS: 1
            TESTS: basic
            topsrcdir: "{{srcdir}}"
            commondir: "{{srcdir}}/tests/common"
          args:
            chdir: "{{srcdir}}"

        always:
        - name: Fetch test results
          command: rsync -a --delete {{srcdir}}/vmcheck/ {{artifacts}}/vmcheck