- name: Deploy Traefik Reverse Proxy
  hosts: all
  remote_user: root
  pre_tasks:
  - name: "Assert config_dir is provided and not empty"
    assert:
      that:
        - config_dir is not undefined and config_dir != ""

  tasks:

  ##
  - name: "Create config directory"
    file:
      path: "{{ config_dir }}"
      state: directory
      recurse: yes

  - name: "Create config sub-directory certs"
    file:
      path: "{{ config_dir }}/certs"
      state: directory
      recurse: yes

  - name: "Create config sub-directory traefik-config"
    file:
      path: "{{ config_dir }}/traefik-config"
      state: directory
      recurse: yes
  ##

  - name: "Upload config file: {{ config_dir }}/traefik.toml"
    copy:
      src: "traefik/traefik.toml"
      dest: "{{ config_dir }}/traefik.toml"

  - name: "Upload config file: {{ config_dir }}/traefik-config/auth-middleware.yml"
    copy:
      src: "traefik/auth-middleware.yml"
      dest: "{{ config_dir }}/traefik-config/auth-middleware.yml"

  - name: "Upload config file: {{ config_dir }}/traefik-config/certificates.yml"
    copy:
      src: "traefik/certificates.yml"
      dest: "{{ config_dir }}/traefik-config/certificates.yml"

  ##
  - name: "Check if \"{{ config_dir }}/certs/cert.pem\" file exists"
    stat:
      path: "{{ config_dir }}/certs/cert.pem"
    register: certfile

  - name: "copy file: \"{{ config_dir }}/certs/cert.pem\" if it doesn't exist"
    copy: 
      src: traefik/cert.pem
      dest: "{{ config_dir }}/certs/cert.pem"
    when: not certfile.stat.exists


  - name: "Check if \"{{ config_dir }}/certs/key.pem\" file exists"
    stat:
      path: "{{ config_dir }}/certs/key.pem"
    register: keyfile

  - name: "copy file: \"{{ config_dir }}/certs/key.pem\" if it doesn't exist"
    copy: 
      src: traefik/key.pem
      dest: "{{ config_dir }}/certs/key.pem"
    when: not keyfile.stat.exists
  ##

  - name: Execute docker-compose
    shell: cd "{{ config_dir }}" && docker-compose down
    ignore_errors: true

  - name: "Upload docker-compose template"
    template:
      src: templates/docker-compose-traefik.yml
      dest: "{{ config_dir }}/docker-compose.yml"

  - name: "Create traefik docker network"
    shell: docker network create --driver=bridge --subnet=172.28.0.0/16 --ip-range=172.28.5.0/24 --gateway=172.28.5.254 traefik_http
    ignore_errors: yes

  - name: Execute docker-compose
    shell: cd "{{ config_dir }}" && docker-compose up -d
