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

# {{ ansible_managed }}

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

docker_pkg = loads('''{{ docker_server__packagename | to_nice_json }}''')
daemon_json = '/etc/docker/daemon.json'


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)
    )


def cmd_abspath(cmd):
    binaries = (os.path.abspath(os.path.join(path, cmd))
                for path in os.environ["PATH"].split(os.pathsep))
    for binary in binaries:
        if os.access(binary, os.X_OK):
            return binary


output = loads('''{{
    {"upstream": (ansible_local.docker_server.upstream
                  if (ansible_local|d() and
                      ansible_local.docker_server|d() and
                      ansible_local.docker_server.upstream|d())
                  else docker_server__upstream) | bool
    } | to_json }}''')

output['installed'] = cmd_exists('docker')
try:
    version_stdout = subprocess.check_output(
        ["dpkg-query", "-W", "-f=${Version}\n'", docker_pkg]
    ).decode('utf-8').split('+')[0]

    match = re.search(r'^(?:[^:]:)?(?P<docker_version>[^~]+)', version_stdout)
    if match:
        output['version'] = match.group('docker_version')

except Exception:
    pass

try:
    output['dockerd_binary'] = cmd_abspath('dockerd')
except Exception:
    pass

if os.path.exists(daemon_json) and os.path.isfile(daemon_json):
    try:
        with open(daemon_json, 'r') as f:
            daemon_config = load(f)
            output['storage_driver'] = daemon_config['storage-driver']

    except Exception:
        pass

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