---

- hosts: servers[0]
  remote_user: root
  handlers:
    - name: reload systemd daemon
      command: systemctl daemon-reload
    - name: restart camera-download service
      systemd:
        name: camera-download@{{item}}.service
        state: restarted
      with_items: "{{groups.cameras}}"
  tasks:
    - name: install debian packages
      apt:
        pkg:
          - gphoto2
          - fping
    - name: camera-download script
      copy:
        content: |
          #!/usr/bin/fish
          source /etc/camera-download/$argv[1].fish
          cd $dir
          while sleep 1
            echo waiting for PING reply from $ip
            if fping -4 -r60 -B1 -p5000 -q $ip
              echo got PING reply from $ip - starting camera download
              gphoto2 --port ptpip:$ip --get-all-files --skip-existing --force-overwrite --recurse --delete-all-files
            end
          end
        dest: /usr/local/bin/camera-download
        mode: 0755
      notify: restart camera-download service
    - name: camera-download config directory
      file:
        path: /etc/camera-download
        state: directory
    - name: camera-download config
      copy:
        content: |
          set ip {{hostvars[item].ip}}
          set dir {{hostvars[item].camera_download_directory}}
        dest: /etc/camera-download/{{item}}.fish
      with_items: "{{groups.cameras}}"
      notify: restart camera-download service
    - name: camera-download systemd service
      copy:
        content: |
          [Unit]
          Description=run camera-download

          [Service]
          User={{camera_download_user}}
          Group={{camera_download_group}}
          Type=simple
          ExecStart=/usr/local/bin/camera-download %i

          [Install]
          WantedBy=multi-user.target
        dest: /etc/systemd/system/camera-download@.service
      notify:
        - reload systemd daemon
        - restart camera-download service
    - name: enable and start camera-download service
      systemd:
        name: camera-download@{{item}}.service
        state: started
        enabled: yes
      with_items: "{{groups.cameras}}"
