#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
  This script loads optional roles from 'Roles.yaml', provided such a file
  exists and contains valid YAML. Puppet invokes this script as its External
  Node Classifier. See <http://docs.puppetlabs.com/guides/external_nodes.html>
  for details.

"""
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

import io
import os
import re
import syslog
import yaml

# Migrate Roles.yaml -> Roles
try:
    os.rename('/vagrant/Roles.yaml', '/vagrant/Roles')
except Exception:
    pass


classes = []
manifest = {'classes': classes}
try:
    with open('/vagrant/Roles') as f:
        for line in f:
            line = re.sub('(^\s*-\s*|[#%].*$)', '', line).strip()
            if line not in ('', '--', 'classes:'):
                classes.append(line)
except IOError:
    # OK -- No Roles.yaml file.
    pass
except Exception as e:
    err = '{0.__class__.__name__}: {0.args}'.format(e)
    syslog.syslog(syslog.LOG_ERR, err)
finally:
    print(yaml.dump(manifest))
