---
# file: roles/borgbackup/tasks/app.yml

- block:

    - name: Ensure directories
      file:
        path: '{{ application_root }}/{{ item }}'
        state: directory
        mode: 0775
      with_items:
        - borgconfig
        - borgdata/ssh

    - name: Environment file
      copy:
        content: BORG_PASSPHRASE={{ borg_passphrase }}
        dest: '{{ application_root }}/borgconfig/.env'
        owner: root
        group: root
        mode: 0644

    - name: SSH Key
      copy:
        content: '{{ borg_ssh_key }}'
        dest: '{{ application_root }}/borgdata/ssh/id_rsa'
        owner: root
        group: root
        mode: 0600
      # @todo at this point, docker compose project is not running yet.
      #notify:
      #  - Init Borg App

    - name: SSH Config
      copy:
        content: StrictHostKeyChecking no
        dest: '{{ application_root }}/borgdata/ssh/config'
        owner: root
        group: root
        mode: 0600

    - name: Configuration file
      template:
        src: app.yaml
        dest: '{{ application_root }}/borgconfig/config.yaml'
        mode: 0600
      when: ansible_distribution_major_version != '18'

    - name: Crontabs
      copy:
        content: |
          55 */6 * * * PATH=$PATH:/usr/bin /usr/local/bin/borgmatic --stats -v 0 2>&1 && {{ lookup('healthchecks', '', user='root', jobname=['Backup', application, application_id]|join(' '), schedule='55 */6 * * *', disabled=crons_disabled|default(false)) }}
          30 23 1 * * PATH=$PATH:/usr/bin /usr/local/bin/borgmatic check -v 0 2>&1 && {{ lookup('healthchecks', '', user='root', jobname=['Check Backup', application, application_id]|join(' '), schedule='30 23 1 * *', disabled=crons_disabled|default(false)) }}
        dest: '{{ application_root }}/borgconfig/crontab.txt'
        owner: root
        group: root
        mode: 0644

    - name: Docker compose service
      set_fact:
        docker_compose_borgmatic_service:
          image: 'b3vis/borgmatic:1.8'
          restart: unless-stopped
          volumes:
            - /etc/timezone:/etc/timezone:ro
            - /etc/localtime:/etc/localtime:ro
            - /usr/local/bin/alertalerta.py:/usr/local/bin/alertalerta.py
            - '{{ application_backup_source }}:/mnt/source:ro'
            - '{{ application_root }}/borgconfig:/etc/borgmatic.d/'
            - '{{ application_root }}/borgdata/files:/mnt/borg-repository'
            - '{{ application_root }}/borgdata/config:/root/.config/borg'
            - '{{ application_root }}/borgdata/ssh:/root/.ssh'
            - '{{ application_root }}/borgdata/cache:/root/.cache/borg'
          env_file: './borgconfig/.env'

  tags:
    - deploy
