- name: Deploy Dockerized WordPress and MySQL using images from GitLab and Harbor
  hosts: all
  become: true
  gather_facts: true
  remote_user: root

  vars:
    wordpress_image: "gitlab.noris.net:5050/smartika/aop1-projekte:latest"
    db_image: "harbor.noris.net/docker.io/library/mariadb:11"
    project_name: wordpress_stack
    mysql_root_password: "changeme"  # replace securely in real usage

  tasks:

    - name: Install Docker and dependencies
      apt:
        name:
          - docker.io
          - python3-pip
          - python3-requests
          - docker-compose
          - ca-certificates
          - curl
          - gnupg
          - lsb-release
        state: present
        update_cache: yes

    - name: Ensure Docker is running
      systemd:
        name: docker
        state: started
        enabled: true

    - name: Login to GitLab container registry
      community.docker.docker_login:
        registry_url: gitlab.noris.net:5050
        username: "{{ gitlab_username }}"
        password: "{{ gitlab_password }}"
      no_log: true

    - name: Login to Harbor container registry
      community.docker.docker_login:
        registry_url: harbor.noris.net
        username: "{{ gitlab_username }}"
        password: "{{ gitlab_password }}"
      no_log: true

    - name: Pull WordPress image
      community.docker.docker_image:
        name: "{{ wordpress_image }}"
        source: pull

    - name: Pull MariaDB image
      community.docker.docker_image:
        name: "{{ db_image }}"
        source: pull

    - name: Run WordPress + MariaDB stack using docker_compose
      community.docker.docker_compose:
        project_name: "{{ project_name }}"
        recreate: always
        remove_orphans: true
        pull: yes
        definition:
          version: "3.8"
          services:
            db:
              image: "{{ db_image }}"
              restart: always
              environment:
                MYSQL_DATABASE: wordpress
                MYSQL_USER: wordpress
                MYSQL_PASSWORD: "{{ mysql_root_password }}"
                MYSQL_ROOT_PASSWORD: "{{ mysql_root_password }}"
              volumes:
                - db_data:/var/lib/mysql

            wordpress:
              image: "{{ wordpress_image }}"
              ports:
                - "1337:80"
              environment:
                WORDPRESS_DB_HOST: db
                WORDPRESS_DB_USER: wordpress
                WORDPRESS_DB_PASSWORD: "{{ mysql_root_password }}"
                WORDPRESS_DB_NAME: wordpress
              volumes:
                - wp_data:/data
              depends_on:
                - db
          volumes:
            db_data: {}
            wp_data: {}
