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

# {{ ansible_managed }}

from __future__ import print_function
from json import loads, dumps
from sys import exit
from operator import itemgetter
import os

# Workaround for Jinja template in a Python script
"""
{% set root_account__tpl_facts = {
  "configured": True,
  "ssh_authorized_keys": False,
  "ssh_key": (root_account__generate_ssh_key | bool),
  "ssh_key_type": root_account__ssh_key_type,
  "ssh_key_file": (root_account__ssh_key_file + '.pub')
} %}
"""

output = loads('''{{ root_account__tpl_facts | to_nice_json }}''')

if (os.path.isfile('/root/.ssh/authorized_keys')
        and os.stat('/root/.ssh/authorized_keys').st_size > 0):
    output['ssh_authorized_keys'] = True

if output['ssh_key']:

    if os.path.isfile(output['ssh_key_file']):
        try:
            fh = open(output['ssh_key_file'])
            for line in fh:
                output.update({"ssh_public_key": line})
            fh.close()

        except Exception:
            pass

if os.path.exists('/etc/subuid') and os.path.isfile('/etc/subuid'):
    try:
        subuid_list = []
        subgid_list = []
        with open('/etc/subuid', 'r') as f:
            for line in f:
                if line.startswith('root:'):
                    parts = line.strip().split(':')
                    subuid_list.append({'start': parts[1],
                                        'count': parts[2]})
        with open('/etc/subgid', 'r') as f:
            for line in f:
                if line.startswith('root:'):
                    parts = line.strip().split(':')
                    subgid_list.append({'start': parts[1],
                                        'count': parts[2]})
            output.update({'subuids': sorted(subuid_list,
                                             key=itemgetter('start'))})
            output.update({'subgids': sorted(subgid_list,
                                             key=itemgetter('start'))})

    except Exception:
        pass

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