---
- hosts:
  - tag_openshift_master
  - tag_openshift_infra
  - tag_openshift_node
  - tag_openshift_lb
  tasks:
  - name: Allow rhsm a longer timeout to help out with subscription-manager
    lineinfile:
      dest: /etc/rhsm/rhsm.conf
      line: 'server_timeout=600'
      insertafter: '^proxy_password ='

  - name: Is the host already registered?
    command: "subscription-manager version"
    register: subscribed
    changed_when: no
    ignore_errors: yes

  - name: Install Katello RPM if set
    yum:
      name: "{{ rhsm_katello_url }}"
      state: present
    when: rhsm_katello_url is defined and rhsm_katello_url

  - name: Register host via Activation key
    redhat_subscription:
      activationkey: "{{ rhsm_activation_key }}"
      org_id: "{{ rhsm_org_id }}"
      state: present
      pool: "{{ rhsm_pool }}"
    when: rhsm_activation_key is defined and rhsm_activation_key
    register: register_key_result
    ignore_errors: yes

  - name: Register host
    redhat_subscription:
      username: "{{ rhsm_user }}"
      password: "{{ rhsm_password }}"
      server_hostname: "{{ rhsm_server }}"
      state: present
      pool: "{{ rhsm_pool }}"
    when: "('not registered' in subscribed.stdout or 'Current' not in subscribed.stdout) and rhsm_user is defined and rhsm_user"

  - name: Check if subscription is attached
    command: "subscription-manager list --consumed --pool-only --matches='{{ rhsm_pool }}'"
    register: subscription_attached
    when: rhsm_pool is defined and rhsm_pool
    changed_when: no

  - block:
    - name: Get pool id
      shell: "subscription-manager list --available --pool-only --matches='{{ rhsm_pool }}' | head -n 1"
      register: pool_id
      changed_when: no

    - name: Fail if no pool ID is returned
      fail:
        msg: No subscription matching "{{ rhsm_pool }}" found
      when: pool_id.stdout == ""

    - name: Attach subscription
      command: "subscription-manager attach --pool={{ pool_id.stdout }}"

    when:
    - rhsm_pool is defined
    - subscription_attached.stdout == ''

  - name: Install katello-agent RPM if we are using satellite
    yum:
      name: katello-agent
      state: present
    when: rhsm_katello_url is defined and rhsm_katello_url
