---
- name: Generate a random string for test
  set_fact:
    test_id: "{{ lookup('password', '/dev/null chars=ascii_letters length=16') }}"
  when: test_id is not defined

- name: Generate names
  set_fact:
    inv_name: "AWX-Collection-tests-tower_tower_ad_hoc_command_cancel-inventory-{{ test_id }}"
    ssh_cred_name: "AWX-Collection-tests-tower_tower_ad_hoc_command_cancel-ssh-cred-{{ test_id }}"
    org_name: "AWX-Collection-tests-tower_tower_ad_hoc_command_cancel-org-{{ test_id }}"

- name: Create a New Organization
  tower_organization:
    name: "{{ org_name }}"

- name: Create an Inventory
  tower_inventory:
    name: "{{ inv_name }}"
    organization: "{{ org_name }}"
    state: present

- name: Add localhost to the Inventory
  tower_host:
    name: localhost
    inventory: "{{ inv_name }}"
    variables:
      ansible_connection: local

- name: Create a Credential
  tower_credential:
    name: "{{ ssh_cred_name }}"
    organization: "{{ org_name }}"
    credential_type: 'Machine'
    state: present

- name: Launch an Ad Hoc Command
  tower_ad_hoc_command:
    inventory: "{{ inv_name }}"
    credential: "{{ ssh_cred_name }}"
    module_name: "command"
    module_args: "sleep 100"
  register: command

- assert:
    that:
      - "command is changed"

- name: Timeout waiting for the command to cancel
  tower_ad_hoc_command_cancel:
    command_id: "{{ command.id }}"
    timeout: -1
  register: results
  ignore_errors: true

- assert:
    that:
      - results is failed
      - "results['msg'] == 'Monitoring of ad hoc command aborted due to timeout'"

- name: Cancel the command with hard error if it's not running
  tower_ad_hoc_command_cancel:
    command_id: "{{ command.id }}"
    fail_if_not_running: true
  register: results

- assert:
    that:
      - results is changed

- name: Cancel an already canceled command (assert failure)
  tower_ad_hoc_command_cancel:
    command_id: "{{ command.id }}"
    fail_if_not_running: true
  register: results
  ignore_errors: true

- assert:
    that:
      - results is failed

- name: Check module fails with correct msg
  tower_ad_hoc_command_cancel:
    command_id: 9999999999
  register: result
  ignore_errors: true

- assert:
    that:
      - "result.msg == 'Unable to find command with id 9999999999'"

- name: Delete the Credential
  tower_credential:
    name: "{{ ssh_cred_name }}"
    organization: "{{ org_name }}"
    credential_type: 'Machine'
    state: absent

- name: Delete the Inventory
  tower_inventory:
    name: "{{ inv_name }}"
    organization: "{{ org_name }}"
    state: absent

- name: Remove the Organization
  tower_organization:
    name: "{{ org_name }}"
    state: absent
