---
- name: "{{ env.name }} | Build app image"
  ansible.builtin.command:
    argv:
      - docker
      - build
      - --build-arg
      - "NEXT_PUBLIC_SERVER_URL=https://{{ env.domain }}"
      - --build-arg
      - "NEXT_PUBLIC_SITE_ID={{ env.site_id }}"
      - -t
      - "church-website:{{ env.name }}"
      - "{{ repo_dir }}"
  changed_when: true

- name: "{{ env.name }} | Build migration image"
  ansible.builtin.command:
    argv:
      - docker
      - build
      - --target
      - builder
      - --build-arg
      - "NEXT_PUBLIC_SERVER_URL=https://{{ env.domain }}"
      - --build-arg
      - "NEXT_PUBLIC_SITE_ID={{ env.site_id }}"
      - -t
      - "church-website-migrate:{{ env.name }}"
      - "{{ repo_dir }}"
  changed_when: true

- name: "{{ env.name }} | Run database migrations"
  ansible.builtin.command:
    argv:
      - docker
      - run
      - --rm
      - --network
      - "{{ docker_network }}"
      - --env-file
      - "{{ envs_dir }}/{{ env.name }}/.env"
      - "church-website-migrate:{{ env.name }}"
      - npx
      - payload
      - migrate
  changed_when: true

- name: "{{ env.name }} | Stop old container"
  ansible.builtin.command: "docker stop app-{{ env.name }}"
  failed_when: false
  changed_when: true

- name: "{{ env.name }} | Remove old container"
  ansible.builtin.command: "docker rm app-{{ env.name }}"
  failed_when: false
  changed_when: true

- name: "{{ env.name }} | Start new container"
  ansible.builtin.command:
    argv:
      - docker
      - run
      - -d
      - --name
      - "app-{{ env.name }}"
      - --restart
      - unless-stopped
      - --network
      - "{{ docker_network }}"
      - --env-file
      - "{{ envs_dir }}/{{ env.name }}/.env"
      - -v
      - "uploads-{{ env.name }}-media:/app/media"
      - -v
      - "uploads-{{ env.name }}-documents:/app/documents"
      - -p
      - "127.0.0.1:{{ env.port }}:3000"
      - "church-website:{{ env.name }}"
  changed_when: true

- name: "{{ env.name }} | Fix upload volume permissions"
  ansible.builtin.command:
    argv:
      - docker
      - exec
      - -u
      - "0"
      - "app-{{ env.name }}"
      - chown
      - -R
      - 1001:1001
      - /app/media
      - /app/documents
  changed_when: true

- name: "{{ env.name }} | Prune old Docker images"
  ansible.builtin.command: docker image prune -f
  changed_when: true
