---
- hosts: debian
  become: yes

  tasks:

   - name: Update packages list
     apt: update_cache=yes
     when: ansible_os_family == 'Debian'

   - name: List packages to upgrade (1/2)
     shell: aptitude -q -F%p --disable-columns search "~U"
     register: updates
     changed_when: False
     when: ansible_os_family == 'Debian'

   - name: List packages to upgrade (2/2)
     debug: msg="{{ updates.stdout_lines | count }} packages to upgrade ({{ updates.stdout_lines | join(', ') }})"
     when: (ansible_os_family == 'Debian' and updates.stdout_lines)

   - name: Upgrade packages
     apt: upgrade=safe
     when: ansible_os_family == 'Debian'

   - name: Check what the new version is
     shell:  lsb_release -r | awk '{print $2}'
     changed_when: False
     register: new_release

   - name: /jessie/ install the needrestart package if it is missing
     apt: name=needrestart state=present default_release=jessie-backports
     when: ansible_distribution_release == 'jessie'

   - name: /jessie/ list services to restart (1/3)
     shell: needrestart -blrl | awk '/^NEEDRESTART-SVC/{print $2}'
     register: services
     changed_when: False
     when: ansible_distribution_release == 'jessie'

#   - name: /jessie/ merge services list (2/3)
#     set_fact:
#       services: "{{ services }}"

#   - name: list services to restart (3/3)
#     debug: msg="{{ services.stdout_lines | count }} services to restart ({{ services.stdout_lines | join (", ") }})"
#     when: (ansible_os_family == 'Debian' and services.stdout_lines)

#   - name: list services to restart (2/3)
#     debug: msg="{{ services.stdout_lines | count }} services to restart ({{ services.stdout_lines | join (", ") }})"
#     when: (ansible_os_family == 'Debian' and services.stdout_lines)

   - name: cache cleanup
     shell: apt-get autoclean
