- name: Ensure bot directories
  file:
    state: directory
    path: '/var/lib/matrix-gerritbot/{{ item }}'
    mode: 0700
  loop:
    - config
    - ssh

- name: Install gerritbot config
  copy:
    src: gerritbot.yaml
    dest: /var/lib/matrix-gerritbot/config/gerritbot.yaml
  register: _gerritbot_config

- name: Lookup the configuration schema
  command: docker run --rm "{{ gerritbot_matrix_image }}" print-config-schema
  register: _gerritbot_schema

- name: Validate and create the configuration
  when: _gerritbot_config.changed
  shell: >-
    cat {{ config }}/gerritbot.yaml | {{ yaml_to_dhall }} "{{ schema }}"
    --output {{ config }}/gerritbot.dhall
  vars:
    config: /var/lib/matrix-gerritbot/config
    yaml_to_dhall: >-
      docker run -i -v {{ config }}:{{ config }}
      --rm docker.io/dhallhaskell/dhall-yaml yaml-to-dhall
    schema: "List {{ _gerritbot_schema.stdout }}"

- name: Install gerritbot ssh key
  copy:
    content: "{{ gerritbot_ssh_key }}"
    dest: "/var/lib/matrix-gerritbot/ssh/id_{{ gerritbot_ssh_key_format }}"
    mode: 0400
  no_log: true

- name: Install gerritbot ssh key
  copy:
    content: "{{ gerritbot_ssh_pubkey }}"
    dest: "/var/lib/matrix-gerritbot/ssh/id_{{ gerritbot_ssh_key_format }}.pub"

- name: Install gerritbot known host
  copy:
    content: "{{ gerritbot_known_hosts }}"
    dest: "/var/lib/matrix-gerritbot/ssh/known_hosts"

- name: Ensure /etc/matrix-gerritbot-docker directory
  file:
    state: directory
    path: /etc/matrix-gerritbot-docker
    mode: 0755

- name: Put docker-compose file in place
  template:
    src: docker-compose.yaml.j2
    dest: /etc/matrix-gerritbot-docker/docker-compose.yaml
    # The token is written into the file
    mode: 0600

- name: Run docker-compose up
  shell:
    cmd: "docker-compose up -d"
    chdir: /etc/matrix-gerritbot-docker/

- name: Run docker prune to cleanup unneeded images
  shell:
    cmd: docker image prune -f