#!/usr/bin/env python

# script to generate an /etc/hosts file with ip addrs
# and role-based hostnames for linodes   
#
# sys.argv[1] - ansible inventory file generated by linode-launch.py

import sys

with open(sys.argv[1], 'r') as f:
    lines = [ l.strip() for l in f.readlines() ]

groups = {}
for l in lines:
    if l == '':
        pass

    elif l.startswith('[') and l.endswith(']'):
        group_nm = l.split('[')[1].split(']')[0][:-1]
        groups[group_nm] = []

    elif l.__contains__('='):
        # typical ansible inventory file record generated by ceph-linode:
        # client-002 ansible_ssh_host=192.168.198.107 ansible_ssh_port=22 ansible_ssh_user='root' ansible_ssh_private_key_file='/root/.ssh/id_rsa'
	a = l.split()[1].split('=')[1]
	hostnm=l.split()[0]
        groups[group_nm].append((hostnm,a))

# output default /etc/hosts file contents

print('127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4')
print('::1         localhost localhost.localdomain localhost6 localhost6.localdomain6')

# append ansible role hostnames and IP addresses to that.

for g in groups.keys():
    for (hostnm, a) in groups[g]:
        print('%s %s' % (a, hostnm))
