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

# {{ ansible_managed }}

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


def cmd_exists(cmd):
    return any(
        os.access(os.path.join(path, cmd), os.X_OK)
        for path in os.environ["PATH"].split(os.pathsep)
    )


output = loads('''{{ {"installed": False,
                      "configured": True}
                     | to_nice_json }}''')

output['installed'] = cmd_exists('icinga2')

try:
    icinga_version_stdout = subprocess.check_output(
            ["dpkg-query", "-W", "-f=${Version}\n'",
             "icinga2"]).decode('utf-8').split('-')[0]
    output['version'] = icinga_version_stdout

except Exception:
    pass

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