- name: Install packages
  tags: packages
  apt:
    name:
      - borgbackup
    install_recommends: no

- name: "mkdir /etc/tergum/jobs/{{ borg_job__name }}"
  file:
    path: "/etc/tergum/jobs/{{ borg_job__name }}"
    state: directory

- name: "/etc/tergum/jobs/{{ borg_job__name }}/env"
  copy:
    dest: "/etc/tergum/jobs/{{ borg_job__name }}/env"
    content: |
      BORG_REPO={{ borg_job__username }}@{{ borg_job__target }}:borg/{{ ansible_hostname }}/{{ borg_job__name }}
      BORG_RSH=ssh -i /etc/tergum/ssh-key -o GlobalKnownHostsFile=/etc/tergum/ssh_known_hosts
      BORG_PASSPHRASE={{ borg__passphrases[ansible_hostname][borg_job__name] }}
      {% if borg_job__borg_remote_path is defined %}
      BORG_REMOTE_PATH={{ borg_job__borg_remote_path }}
      {% endif %}

#      BORG_KEYS_DIR
#      BORG_SECURITY_DIR
#      BORG_CACHE_DIR

- name: "/etc/tergum/jobs/{{ borg_job__name }}/patterns"
  copy:
    dest: "/etc/tergum/jobs/{{ borg_job__name }}/patterns"
    content: "{{ borg_job__settings.patterns }}"

- name: "/etc/tergum/jobs/{{ borg_job__name }}/excludes"
  vars:
    excludes: "{{ borg_job__settings.excludes if borg_job__settings.excludes is defined else [] }}"
  copy:
    dest: "/etc/tergum/jobs/{{ borg_job__name }}/excludes"
    content: |
      {% for item in excludes %}
      {{ item }}
      {% endfor %}
      {% for item in borg_job__default_excludes %}
      {{ item }}
      {% endfor %}

- file:
    path: "/etc/systemd/system/tergum@{{ borg_job__name }}.timer.d"
    state: directory

- copy:
    dest: "/etc/systemd/system/tergum@{{ borg_job__name }}.timer.d/override.conf"
    content: |
      [Timer]
      OnCalendar={{ borg_job__settings.on_calendar if borg_job__settings.on_calendar is defined else borg_job__on_calendar }}
  notify:
    - systemctl daemon-reload

- meta: flush_handlers

- systemd:
    name: "tergum@{{ borg_job__name }}.timer"
    enabled: yes
    state: started