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

# {{ ansible_managed }}

from __future__ import print_function
from json import loads, dumps
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 = {'installed': cmd_exists('minio')}

try:
    minio_version_stdout = subprocess.check_output(
            ["minio", "--version"]
            ).decode('utf-8').strip()
except Exception:
    try:
        minio_version_stdout = subprocess.check_output(
                ["minio", "version"]
                ).decode('utf-8').strip()
    except Exception:
        pass

if minio_version_stdout:
    for line in minio_version_stdout.split('\n'):
        if line.lower().startswith('minio version '):
            output['version'] = line.split()[2]
            output['release_tag'] = line.split()[2]
        elif line.lower().startswith('version: '):
            output['version'] = line.split()[1]
        elif line.lower().startswith('release-tag: '):
            output['release_tag'] = line.split()[1]
        elif line.lower().startswith('commit-id: '):
            output['commit_id'] = line.split()[1]

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