---
- name: Ensure ssh config exists for unifi controller
  become: true
  blockinfile:
    dest: "/root/.ssh/config"
    create: yes
    block: |
      Host unifi
        IdentityFile ~/.ssh/id_rsa.unifi-controller
    marker: "# {mark} ANSIBLE MANAGED BLOCK unifi_controller"
  tags:
    - unifi-controller

- name: Ensure backup service exists
  become: yes
  copy:
    content: |
      [Unit]
      Description=Rsync backup of unifi controller
      OnFailure=status-email@%n.service

      [Service]
      Type=oneshot
      ExecStart=/usr/bin/rsync -a --delete -e ssh root@unifi:/var/lib/unifi/ /shared/backup/unifi-controller/
    dest: /etc/systemd/system/unifi-backup.service
    mode: 0644
    owner: root
  tags:
    - unifi-controller

- name: Ensure backup timer exists
  become: yes
  copy:
    content: |
      [Unit]
      Description=Unifi controller backup
      Wants=network-online.target
      After=network-online.target

      [Timer]
      OnCalendar=18:00
      Persistent=True
      RandomizedDelaySec=600

      [Install]
      WantedBy=timers.target
    dest: /etc/systemd/system/unifi-backup.timer
    mode: 0644
    owner: root
  tags:
    - unifi-controller

---
- name: Ensure ssh config exists for unifi controller
  become: true
  blockinfile:
    dest: "/root/.ssh/config"
    create: yes
    block: |
      Host unifi
        IdentityFile ~/.ssh/id_rsa.unifi-controller
    marker: "# {mark} ANSIBLE MANAGED BLOCK unifi_controller"
  tags:
    - unifi-controller

- name: Add hosts as known hosts
  become: yes
  known_hosts:
    path: "{{ ansible_user_dir }}/.ssh/known_hosts"
    name: "unifi"
    key: "{{ lookup('pipe', 'ssh-keyscan -t rsa unifi') }}"
  tags:
    - unifi-controller

- name: Ensure backup service exists
  become: yes
  copy:
    content: |
      [Unit]
      Description=Rsync backup of unifi controller
      OnFailure=status-email@%n.service

      [Service]
      Type=oneshot
      ExecStart=/usr/bin/rsync -a --delete -e ssh root@unifi:/var/lib/unifi/ /shared/backup/unifi-controller/
    dest: /etc/systemd/system/unifi-backup.service
    mode: 0644
    owner: root
  tags:
    - unifi-controller

- name: Ensure backup timer exists
  become: yes
  copy:
    content: |
      [Unit]
      Description=Unifi controller backup
      Wants=network-online.target
      After=network-online.target

      [Timer]
      OnCalendar=18:00
      Persistent=True
      RandomizedDelaySec=600

      [Install]
      WantedBy=timers.target
    dest: /etc/systemd/system/unifi-backup.timer
    mode: 0644
    owner: root
  tags:
    - unifi-controller

Add host to known hosts
Add host to known hosts
