---
# Restart application containers after file upload

- name: Restart Application Containers
  hosts: all
  become: yes
  vars_files:
    - inventory/group_vars.yml
  
  tasks:
    - name: Check if app directory exists
      stat:
        path: "{{ app_directory }}"
      register: app_dir_exists
      
    - name: Fail if app directory doesn't exist
      fail:
        msg: "App directory {{ app_directory }} not found. Please deploy first with deploy.yml"
      when: not app_dir_exists.stat.exists
      
    - name: Check which docker compose command is available
      shell: |
        if docker compose version >/dev/null 2>&1; then
          echo "docker compose"
        elif docker-compose --version >/dev/null 2>&1; then
          echo "docker-compose"
        else
          echo "none"
        fi
      register: docker_compose_cmd
      changed_when: false

    - name: Fail if docker compose not available
      fail:
        msg: "Neither 'docker compose' nor 'docker-compose' is available"
      when: docker_compose_cmd.stdout == "none"

    - name: Show current container status
      shell: "cd {{ app_directory }} && {{ docker_compose_cmd.stdout }} ps"
      register: container_status_before
      ignore_errors: yes
      changed_when: false

    - name: Stop existing containers
      shell: "cd {{ app_directory }} && {{ docker_compose_cmd.stdout }} down"
      register: stop_result

    - name: Start containers with updated files
      shell: "cd {{ app_directory }} && {{ docker_compose_cmd.stdout }} up -d --build"
      register: start_result

    - name: Wait for application to start
      wait_for:
        port: "{{ app_port }}"
        host: "127.0.0.1"
        delay: 5
        timeout: 60

    - name: Test if app is accessible
      uri:
        url: "http://127.0.0.1:{{ app_port }}/"
        method: GET
        status_code: [200, 301, 302]
      register: app_test
      ignore_errors: yes

    - name: Show final container status
      shell: "cd {{ app_directory }} && {{ docker_compose_cmd.stdout }} ps"
      register: container_status_after
      changed_when: false

    - name: Show restart result
      debug:
        msg: |
          🔄 Application restart completed!
          
          📂 Directory: {{ app_directory }}
          🐳 Docker Compose: {{ docker_compose_cmd.stdout }}
          
          🚀 Restart status: {{ 'Success' if start_result.rc == 0 else 'Failed' }}
          
          {% if app_test.status is defined and (app_test.status == 200 or app_test.status == 301 or app_test.status == 302) %}
          ✅ App is responding (HTTP {{ app_test.status }})
          🌐 Available at: https://{{ domain }}
          {% else %}
          ⚠️  App health check failed - please check logs
          🔍 Check logs with: cd {{ app_directory }} && {{ docker_compose_cmd.stdout }} logs
          {% endif %}
          
          📊 Container Status:
          {{ container_status_after.stdout }}
