---
- name: Deploy Dockerized WordPress and MySQL using images from GitLab Registry
  hosts: all
  gather_facts: yes
  remote_user: root

  vars:
    wordpress_image: "gitlab.noris.net:5050/smartika/aop1-projekte:latest"
    db_image: "mysql:8.0"
    compose_dir: "/opt/wordpress"
    compose_file: "/opt/wordpress/docker-compose.yaml"

  tasks:
    - name: Ensure pip is installed
      apt:
        name: python3-pip
        state: present
      become: yes

    - name: Install python3-requests via apt
      apt:
        name: python3-requests
        state: present
      become: yes

    - name: Install prerequisites for Docker
      apt:
        name:
          - ca-certificates
          - curl
          - gnupg
          - lsb-release
        state: present
        update_cache: yes

    - name: Create Docker keyrings directory
      file:
        path: /etc/apt/keyrings
        state: directory
        mode: '0755'

    - name: Download Docker GPG key
      get_url:
        url: https://download.docker.com/linux/debian/gpg
        dest: /etc/apt/keyrings/docker.asc
        mode: '0644'

    - name: Remove any broken Docker repo entries
      file:
        path: /etc/apt/sources.list.d/docker.list
        state: absent

    - name: Add Docker APT repository
      apt_repository:
        repo: "deb [arch=amd64 signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/debian {{ ansible_lsb.codename }} stable"
        state: present
        filename: docker

    - name: Update apt cache
      apt:
        update_cache: yes

    - name: Install Docker and Compose
      apt:
        name:
          - docker-ce
          - docker-ce-cli
          - containerd.io
          - docker-buildx-plugin
          - docker-compose-plugin
        state: present

    - name: Create project directory
      file:
        path: "{{ compose_dir }}"
        state: directory
        mode: '0755'

    - name: Copy Docker Compose files
      copy:
        src: files/
        dest: "{{ compose_dir }}/"
        mode: '0755'

    - name: Patch Compose to use GitLab WordPress image
      replace:
        path: "{{ compose_file }}"
        regexp: 'image:\s*.*wordpress.*'
        replace: "image: {{ wordpress_image }}"

    - name: Patch Compose to use official MySQL image
      replace:
        path: "{{ compose_file }}"
        regexp: 'image:\s*.*(mysql|mariadb).*'
        replace: "image: {{ db_image }}"

    - name: Login to GitLab Docker Registry (optional, if needed)
      command: docker login -u <GITLAB_USERNAME> -p <GITLAB_ACCESS_TOKEN> gitlab.noris.net:5050
      when: docker_login_required | default(false)

    - name: Pull updated images (WordPress & MySQL)
      command: docker compose pull
      args:
        chdir: "{{ compose_dir }}"

    - name: Run Docker Compose
      command: docker compose up -d
      args:
        chdir: "{{ compose_dir }}"
