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

- name: Create unix group
  become: yes
  group:
    name: "{{ borg_target__group }}"
    system: yes

- name: Create unix user
  become: yes
  user:
    name: "{{ borg_target__user }}"
    group: "{{ borg_target__group }}"
    shell: "{{ borg_target__shell }}"
    home: "{{ borg_target__home }}"
    system: yes

- name: mkdir repos
  file:
    path: "{{ borg_target__home }}/repos"
    state: directory
    mode: u=rwx,go=
    owner: "{{ borg_target__user }}"
    group: "{{ borg_target__group }}"

- with_dict: "{{ borg_target__clients }}"
  file:
    path: "{{ borg_target__home }}/repos/{{ item.key }}"
    state: directory

- include_tasks: borg-init.yml
  with_dict: "{{ borg_target__clients }}"
  loop_control:
    loop_var: client

- file:
    path: "{{ borg_target__home }}/.ssh"
    state: directory
    mode: u=rx,go=
    owner: "{{ borg_target__user }}"
    group: "{{ borg_target__group }}"

- name: authorized_keys
  tags: xxx
  copy:
    dest: "{{ borg_target__home }}/.ssh/authorized_keys"
    content: |
      tilde={{ '~borg' | expanduser }}
      {% for client, config in borg_target__clients.items() %}
      {% set state=config.state | default('present') %}
      # Client: {{ client }}, state={{state}}
      {% if state == 'present' %}
      {% set key=lookup('file', 'borg/' + client + '/ssh-key.pub') %}
      command="cd {{ borg_target__home }}/repos && borg serve --append-only{% for r in config.repos %} --restrict-to-repository {{ client }}/{{ r }}{% endfor %}",no-port-forwarding,no-X11-forwarding,no-pty,no-agent-forwarding,no-user-rc {{ key }}
      {% endif %}
      {% endfor %}
# "