#!/usr/bin/python
# vim: tabstop=8 expandtab shiftwidth=8 softtabstop=8

import sys
import re
import subprocess
import psycopg2
import traceback

db_params = "dbname=packagemanager user=packagemanager"
vpnca_dir = '/var/lib/VPNCA'
whitespace = re.compile('^[ \n\t\r]*$')

def get_shortname(hostname):
        if '.' in hostname:
                hostname=hostname.split('.')[0]
        return hostname

def print_array(name,data):
        print "%s:" % name
        for a in data:
                print "  - \"%s\"" % a

def add_vpn_node(node,hostname):
        filename = '%s/keys/%s.key' % (vpnca_dir,hostname)
        try:
                with open(filename,'r') as f:
                        key = f.read()
        except:
                print "# key file %s not found" % filename
                return

        filename = '%s/certsbyname/%s.pem' % (vpnca_dir,hostname)
        try:
                cert = ''
                ignore = True
                with open(filename,'r') as f:
                        for l in f.readlines():
                                if l.startswith('-----BEGIN CERTIFICATE-----'):
                                        ignore = False
                                if not ignore:
                                        cert = cert + l
        except:
                print "# certificate file %s not found" % filename
                return

        node['vpn_certificate']=cert
        node['vpn_privatekey']=key

def get_profile_config(node,hostname):
        db = None
        config = None
        properties = []
        try:
                # output = subprocess.check_output('packagemanager showsystem %s' % shortname, shell=True)
                db = psycopg2.connect(db_params)
                cursor = db.cursor()

                sql = "SELECT key,value FROM properties " \
                        + "WHERE category='profile' AND profile_id=" \
                        + "(SELECT profile_id FROM computers WHERE name=%s)"
                cursor.execute(sql,(hostname,))
                properties = cursor.fetchall()

                sql = "SELECT config_extras FROM profiles " \
                        + "WHERE id=" \
                        + "(SELECT profile_id FROM computers WHERE name=%s)"
                cursor.execute(sql,(hostname,))
                result = cursor.fetchone()
                if result != None:
                        config = result[0]
        except:
                print "# database error"
                traceback.print_exc()
                return
        finally:
                if db != None:
                        db.close()

        for name,value in properties:
                if not node.has_key(name):
                        node[name] = value.strip()

        if config != None:
                classes = [ c.strip() for c in config.split(",") ]
                node['classes'] = classes

        return node

def get_host_config(node,hostname):
        shortname = get_shortname(hostname)

        ipaddress = None
        macaddress = None

        db = None
        properties = []
        try:
                db = psycopg2.connect(db_params)
                cursor = db.cursor()
                sql = "SELECT ip_address,mac_address FROM computers WHERE name = %s"
                cursor.execute(sql,(hostname,))
                result = cursor.fetchone()
                if result == None:
                        cursor.execute(sql,(shortname,))
                        result = cursor.fetchone()

                if result == None:
                        return None

                ipaddress,macaddress = result

                sql = "SELECT key,value FROM properties WHERE category='computer' AND computer=%s ORDER BY key"
                cursor.execute(sql,(hostname,))
                properties = cursor.fetchall()
        except:
                print "# database error"
                traceback.print_exc()
                return
        finally:
                if db != None:
                        db.close()

        node['macaddress'] = macaddress
        # node['ipaddress'] = ipaddress
        # node['shortname'] = shortname

        for name,value in properties:
                node[name] = value.strip()

        return node

def print_classes(node):
        print "classes:"
        if node.has_key('classes'):
               for c in node['classes']:
                        print "  -",c
        print

def print_parameters(node):
        print "parameters:"
        for p,v in node.iteritems():
                if v!=None and v!="" and p!='classes':
                        print "  %s: %s" % (p,v)

if __name__ == '__main__':

        hostname = sys.argv[1]

        shortname = get_shortname(hostname)

        node = {}

        get_host_config(node,hostname)
        get_profile_config(node,hostname)
        add_vpn_node(node,hostname)

        print_classes(node)
        print_parameters(node)

	print
