# Copyright 2020 Dell Inc. or its subsidiaries. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
---

# Check accessibility of AWX-UI
- name: Re-install if in migrating state
  block:
    - name: Wait for AWX UI to be up
      uri:
        url: "{{ awx_ip }}"
        status_code: "{{ return_status }}"
        return_content: yes
      register: register_error
      until: awx_ui_msg in register_error.content
      retries: 20
      delay: 15
      changed_when: no
      no_log: True

  rescue:
    - name: Starting rescue
      debug:
        msg: "Attempting to re-install AWX"

    - name: Remove old containers
      docker_container:
        name: "{{ item }}"
        state: absent
      loop:
        - awx_task
        - awx_web

    - name: Restart docker
      service:
        name: docker
        state: restarted

    - name: Re-install AWX
      block:
        - name: Run AWX install.yml file
          command: ansible-playbook -i inventory install.yml --extra-vars "admin_password={{ admin_password }}"
          args:
            chdir: "{{ awx_installer_path }}"
          register: awx_installation
          no_log: True

      rescue:
        - name: Check AWX status on machine
          include_tasks: check_awx_status.yml

        - name: Fail if container are not running
          fail:
            msg: "AWX installation failed with error msg:
             {{ awx_installation.stdout | regex_replace(admin_password) }}."
          when: not awx_status

    - name: Check if AWX UI is up
      block:
        - name: Wait for AWX UI to be up
          uri:
            url: "{{ awx_ip }}"
            status_code: "{{ return_status }}"
            return_content: yes
          register: register_error
          until: awx_ui_msg in register_error.content
          retries: 30
          delay: 10
          changed_when: no
          no_log: True
      rescue:
        - name: Message
          fail:
            msg: "{{ register_error | regex_replace(awx_user) | regex_replace(admin_password) }}"
  tags: install