# Ansible playbook to delete a simple Host record (one ipv4addr and/or one
# ipv6addr, no aliases) from IPAM
#
# Example usage: ansible-playbook delete-ipam-host.yml --extra-vars \
#  '{"fqdn":"ansibletest.sandbox.illinois.edu","ipv4addr":"192.168.0.17","ipv6addr":"2001:db8::17"}'
#
# Copyright (c) 2018 Board of Trustees University of Illinois
---
- import_playbook: ipam-provider.yml

- name: Delete IPAM Host record
  hosts: localhost
  gather_facts: false
  vars:

    view: default
    fqdn:
    ipv4addr:
    ipv6addr:

  tasks:

    - assert: { that: "ansible_version.full is version('2.8', '>=')", quiet: true }

    - name: check required variables
      fail: msg="Required variable '{{ item }}' not set"
      when: not lookup('vars', item)
      loop:
        - fqdn

    - name: check required variables (ipv4addr or ipv6addr)
      fail: msg="At least one of ipv4addr or ipv6addr is required"
      when: not ipv4addr and not ipv6addr

    - name: get existing record if any
      set_fact:
        # may return list or single object
        existing_record: "{{ lookup('nios', 'record:host', filter={'view': view, 'name': fqdn},
                                    return_fields=['view', 'name', 'ipv4addrs', 'ipv6addrs', 'ttl', 'use_ttl', 'aliases', 'extattrs', 'comment'],
                                    provider=ipam_provider) }}"

    - debug: var=existing_record
      when: DEBUG is defined

    - when: existing_record
      block:

      - name: check existing Host ipv4addrs
        fail:
          msg: Not deleting mismatched Host '{{fqdn}}'
        when: (not ipv4addr and 'ipv4addrs' in existing_record)
              or (ipv4addr and ('ipv4addrs' not in existing_record
                                or existing_record.ipv4addrs|length > 1
                                or existing_record.ipv4addrs[0].ipv4addr != ipv4addr))

      - name: check existing Host ipv6addrs
        fail:
          msg: Not deleting mismatched Host '{{fqdn}}'
        when: (not ipv6addr and 'ipv6addrs' in existing_record)
              or (ipv6addr and ('ipv6addrs' not in existing_record
                                or existing_record.ipv6addrs|length > 1
                                or existing_record.ipv6addrs[0].ipv6addr != ipv6addr))

      - name: check existing Host aliases
        fail:
          msg: Not deleting mismatched Host '{{fqdn}}'
        when: "'aliases' in existing_record"

    - name: delete Host record
      when: existing_record
      nios_host_record:
        view: "{{ view }}"
        name: "{{ fqdn }}"
        state: absent
        provider: "{{ ipam_provider }}"
