#!/usr/bin/env python

import re
import sys
from subprocess import Popen, PIPE


def main():
    if len(sys.argv) < 2:
        print >>sys.stderr, 'Usage: %s <template>' % sys.argv[0]
        sys.exit(1)

    for template in sys.argv[1:]:
        template = open(template, 'r')
        for line in template.readlines():
            m = re.match('([ \t]*)--(.+)--[ \t]*$', line)
            if m is not None:
                indent = m.group(1)
                for entry in ldapsearch(m.group(2)):
                    print '%s%s' % (indent, entry)
            else:
                sys.stdout.write(line)
        template.close()


def ldapsearch(filter):
    p = Popen(['ldapsearch', '-x', '-z', '0', '-LLL', filter, 'cn', 'macAddress', 'ipHostNumber'],
               bufsize=1024, stdout=PIPE, close_fds=True)
    ret = []
    cur = {}
    for l in p.stdout.readlines():
        l = l.strip()
        if l == '':
            try:
                ret.append('host %s { option host-name "%s"; hardware ethernet %s; fixed-address %s; }' % (
                    cur["cn"], cur["cn"].split('.')[0], cur["macAddress"], cur["ipHostNumber"]))
            except KeyError:
                print >>sys.stderr, "skipping: %s" % repr(cur)
            cur = {}
            continue
        l = l.split()
        if l[0] in ('cn:', 'macAddress:', 'ipHostNumber:'):
                cur[l[0][0:-1]] = l[1]
    return ret


if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        sys.exit()

