---
# file: roles/netdata/tasks/main.yml

- name: "NetData Role"
  set_fact: role_netdata_started=true
  tags: always

- block:

  - name: "Install required packages"
    apt:
      pkg={{ item }}
      state=installed
      update_cache=yes
    with_items:
      - zlib1g-dev
      - gcc
      - make
      - git
      - autoconf
      - autogen
      - automake
      - pkg-config
      - uuid-dev
      - python-dev
      - python-yaml
      #FireQOS available from 15.04
      #- firehol

  - name: "Ensure Directory"
    file:
      path='/etc/netdata/python.d'
      state='directory'

  - include: install.yml

  - name: "Install startup script"
    template:
      src=etc_init_d_netdata
      dest=/etc/init.d/netdata
      owner=root
      group=root
      mode=755
    notify:
      - "Include NetData to Boot-List"
      - "Re-start NetData"

  - name: "Install logrotate script"
    template:
      src=etc_logrotate_d_netdata
      dest=/etc/logrotate.d/netdata
      owner=root
      group=root
      mode=644

  - name: "Configure Registry"
    ini_file:
      dest='/etc/netdata/netdata.conf'
      create=yes
      section='registry'
      option='{{ item.option }}'
      value='{{ item.value }}'
    with_items:
      - option: 'enabled'
        value: '{{ (netdata_registry|default("pmon1") == inventory_hostname)|ternary("yes", "no") }}'
      - option: 'registry to announce'
        value: 'http://{{ netdata_registry|default("pmon1") }}:19999'
    notify:
      - "Re-start NetData"

  - name: "Configure NetData"
    template:
      src='{{ item }}'
      dest='/etc/netdata/{{ item }}'
      owner='root'
      group='root'
      mode=644
      backup=yes
    with_items:
      - 'python.d.conf'
      - 'health_alarm_notify.conf'
    notify:
      - "Re-start NetData"

  - name: "Configure Plugins"
    template:
      src='{{ item }}.conf'
      dest='/etc/netdata/python.d/{{ item }}.conf'
      owner='root'
      group='root'
      mode=644
    with_items:
      - 'mysql'
    notify:
      - "Re-start NetData"

  - name: "Check if KSM is available"
    stat: path='/sys/kernel/mm/ksm'
    register: ksm

  # Note: copy module doesn't work here because parent directory /sys
  # is not writable, not even by root
  - name: "Configure KSM"
    shell: echo {{ item.value }} >/sys/kernel/mm/ksm/{{ item.file }}
    with_items:
      - file: 'run'
        value: '1'
      - file: 'sleep_millisecs'
        value: '1000'
    when: ksm.stat.exists
    notify:
      - "Re-start NetData"

  when: '"netdata" not in excluded_roles'
