---
- name: backup script
  template:
    src: client-backup-script.sh.j2
    dest: "/usr/local/bin/{{ item.value.command }}"
    owner: "{{ item.value.user }}"
    group: "{{ item.value.user }}"
    mode: 0700
  with_dict:
  - "{{ rsnapshot_push.cases }}"
  tags: rsnapshot_push

- name: install rsnapshot package
  package:
    name: rsnapshot
    state: present
  delegate_to: "{{ rsnapshot_push.server_host }}"
  tags: rsnapshot_push

- name: server-side case-specific backup dir
  file:
    path: "{{ '/'.join([rsnapshot_push.backup_dir, item.key]) }}"
    state: directory
    owner: "{{ item.value.user }}"
    group: "{{ item.value.user }}"
    mode: 0700
  with_dict:
    - "{{ rsnapshot_push.cases }}"
  delegate_to: "{{ rsnapshot_push.server_host }}"
  tags: rsnapshot_push

- name: server-side custom rsnapshot daemon script
  template:
    src: server-daemon.sh.j2
    dest: "{{ '/'.join([rsnapshot_push.backup_dir, item.key, 'sync-daemon']) }}"
    owner: "{{ item.value.user }}"
    group: "{{ item.value.user }}"
    mode: 0700
  with_dict:
  - "{{ rsnapshot_push.cases }}"
  delegate_to: "{{ rsnapshot_push.server_host }}"
  tags: rsnapshot_push

- name: install authorized key entry
  authorized_key:
    user: "{{ item.value.user }}"
    state: present
    key: "{{ item.value.ssh_pub_key }}"
    key_options: "command=\"{{ '/'.join([rsnapshot_push.backup_dir, item.key, 'sync-daemon']) }}\""
  delegate_to: "{{ rsnapshot_push.server_host }}"
  with_dict:
    - "{{ rsnapshot_push.cases }}"
  tags: rsnapshot_push

- name: rsnapshot call wrapper
  template:
    src: server-rsnapshot.py.j2
    dest: "{{ '/'.join([rsnapshot_push.backup_dir, item.key, 'rsnapshot']) }}"
    owner: "{{ item.value.user }}"
    group: "{{ item.value.user }}"
    mode: 0700
  with_dict:
  - "{{ rsnapshot_push.cases }}"
  delegate_to: "{{ rsnapshot_push.server_host }}"
  tags: rsnapshot_push

- name: cronjob run twice a week to trigger the backup (and rotation)
  cron:
    name: "rsnapshot_push backup - {{ item.key }}"
    minute: "1"
    hour: "1"
    weekday: "6"
    user: "{{ item.value.user }}"
    job: "ionice --class=idle /usr/local/bin/{{ item.value.command }} >/dev/null"
  with_dict:
    - "{{ rsnapshot_push.cases }}"
  tags: rsnapshot_push
