---

- name: Add ferm rule.
  template:
    dest: /etc/ferm.d/11-in-lockss-frontend.ferm
    src: 11-in-lockss-frontend.ferm.j2
    validate: ferm -n %s

- service:
    name: ferm
    state: restarted

- name: Create temporary directory.
  tempfile:
    state: directory
  register: tmpdir

- name: Install configuration file.
  template:
    dest: "{{ tmpdir.path }}/httpd-frontend.conf"
    src: httpd-frontend.conf.j2
    owner: root
    mode: 0644
  when: tmpdir.path is defined

- name: Install landing page.
  template:
    dest: "{{ tmpdir.path }}/index.html"
    src: index.html.j2
    owner: root
    mode: 0644
  when: tmpdir.path is defined

- name: Install Dockerfile.
  copy:
    dest: "{{ tmpdir.path }}/Dockerfile"
    src: Dockerfile
    owner: root
    mode: 0644
  when: tmpdir.path is defined

- name: Install python3-jsondiff (Ubuntu).
  package:
    name: python3-jsondiff=1.*
    state: present
  when: ansible_distribution == "Ubuntu"

- name: Install needed Python libraries (CentOS).
  vars:
    ansible_python_interpreter: python3
  pip:
    name:
      - jsondiff>=1.0,<2.0
      - pyyaml>=5.0,<6.0
    state: present
  when: ansible_distribution == "CentOS"

- name: Build Docker image.
  docker_image:
    name: lockss-config-frontend
    source: build
    build:
      path: "{{ tmpdir.path }}"
      pull: yes
  when: tmpdir.path is defined

- name: Deploy stack.
  vars:
    ansible_python_interpreter: python3
  docker_stack:
    name: lockss-config-frontend
    state: present
    resolve_image: never
    compose:
      - version: "3.7"
        services:
          frontend:
            image: lockss-config-frontend
            ports:
              - published: "{{ lockss_frontend_port }}"
                target: 80
                mode: host
            configs:
              - source: httpd_frontend_config
                target: /usr/local/apache2/conf/conf.d/frontend.conf
              - source: index
                target: /usr/local/apache2/htdocs/index.html

        configs:
          httpd_frontend_config:
            file: "{{ tmpdir.path }}/httpd-frontend.conf"
          index:
            file: "{{ tmpdir.path }}/index.html"

        networks:
          default:
            external:
              name: host
  when: tmpdir.path is defined

- name: Remove temporary directory.
  file:
    path: "{{ tmpdir.path }}"
    state: absent
  when: tmpdir.path is defined
