#!{{ ansible_python['executable'] }}

# {{ ansible_managed }}

from __future__ import print_function
from json import loads, dumps
from sys import exit
import subprocess
import signal
import os

output = loads('''{{ ({
    "configured": true,
    "heartbeat_override": elastic_co__heartbeat_override,
    "version": elastic_co__version,
    "curator_version": elastic_co__curator_version
}) | to_nice_json }}''')

# List of Elastic APT packages recognized by this fact
package_list = [
  'elasticsearch',
  'elasticsearch-curator',
  'filebeat',
  'kibana',
  'logstash',
  'metricbeat',
  'packetbeat'
]

# A workaround for conflicting package name in Debian/Ubuntu
# https://github.com/elastic/beats/issues/3765
heartbeat_override = loads('''{{ elastic_co__heartbeat_override
                                 | bool | lower | to_nice_json }}''')

if heartbeat_override:
    package_list.append('heartbeat')


def dpkg_query(packages):

    command = ['dpkg-query', '--show',
               '--showformat="${Package}": "${Version}",\n'] + packages

    FNULL = open('/dev/null', 'w')
    proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=FNULL)
    (stdoutdata, _) = proc.communicate()

    stdout_clean = stdoutdata.strip()
    stdout_last = stdout_clean.decode('utf-8').rstrip(',')
    stdout_wrap = '{\n' + stdout_last + '\n}'

    proc_output = loads(str(stdout_wrap))
    return proc_output


package_version = dpkg_query(package_list)
output.update({"packages": package_version})

print(dumps(output, sort_keys=True, indent=4))
