---
- name: Check if restic is installed
  stat:
    path: '{{ restic_path }}'
  register: restic_binary

- include_tasks: install.yml
  when: not restic_binary.stat.exists or restic_install

  # TODO: check if exists?
- name: Overwrite SSH config for backup server
  become: yes
  template:
    src: ssh_config.j2
    dest: '{{ restic_user_home }}/.ssh/config'
    owner: root
    group: root
    mode: '0600'
  when: restic_ssh_enabled

- name: Add SSH private key
  become: yes
  template:
    src: ssh_private_key.j2
    dest: '{{ restic_ssh_private_key_path }}'
    mode: '0600'
  when: restic_ssh_private_key is defined and restic_ssh_enabled

- name: Add backup server host fingerprint
  become: yes
  known_hosts:
    name: '[{{ restic_ssh_hostname }}]:{{ restic_ssh_port }}'
    key: '{{ restic_ssh_host_fingerprint }}'
    path: '{{ restic_user_home }}/.ssh/known_hosts'
    state: present

- name: Add restic_env in home folder
  become: yes
  template:
    src: restic_env.j2
    dest: '{{ restic_user_home }}/.restic_env'
    owner: root
    group: root
    mode: '0600'

- name: Add systemd service for restic
  become: yes
  template:
    src: restic-backup.service.j2
    dest: /etc/systemd/system/restic-backup.service
    mode: '0644'
  vars:
    restic_folders_combined: '{{ restic_default_folders + restic_folders }}'
  notify: systemd reload

- name: Add systemd timer for restic
  become: yes
  template:
    src: restic-backup.timer.j2
    dest: /etc/systemd/system/restic-backup.timer
    mode: '0644'
  notify: systemd reload

- name: Enable and start restic timer
  become: yes
  systemd:
    name: restic-backup.timer
    enabled: true
    state: started

- name: Initialize restic repo if needed
  become: yes
  command: "{{restic_path}} init"
  environment:
    RESTIC_REPOSITORY: "sftp:{{ restic_ssh_host }}:{{ restic_repository_name }}"
    RESTIC_PASSWORD: "{{restic_password}}"
  no_log: true
  register: restic_init
  changed_when: "'created restic repository' in restic_init.stdout"
  failed_when:
    - restic_init.rc != 0
    - not 'config file already exists' in restic_init.stderr
    - not 'config already initialized' in restic_init.stderr
    - not 'config already exists' in restic_init.stderr
