# Path: yubiadmin/util/config.py
# class RegexHandler(object):
#     def __init__(self, pattern, writer, reader=lambda x: x.group(1),
#                  inserter=lambda x, y: '%s\n%s' % (x, y),
#                  default=None):
#         self.pattern = re.compile(pattern)
#         self.writer = writer
#         self.reader = reader
#         self.inserter = inserter
#         self.default = default
# 
#     def read(self, content):
#         match = self.pattern.search(content)
#         if match:
#             return self.reader(match)
#         return self.default
# 
#     def write(self, content, value):
#         if value is None:
#             value = ''
#         if self.pattern.search(content):
#             new_content = self.pattern.sub(self.writer(value), content, 1)
#             if self.read(content) == self.read(new_content):
#                 #Value remains unchanged, don't re-write it.
#                 return content
#             else:
#                 return new_content
#         else:
#             return self.inserter(content, self.writer(value))
# 
# class FileConfig(MutableMapping):
#     """
#     Maps key-value pairs to a backing config file.
#     You can manually edit the file by modifying self.content.
#     """
#     def __init__(self, filename, params=[]):
#         self.filename = filename
#         self.params = OrderedDict()
#         for param in params:
#             self.add_param(*param)
# 
#     def read(self):
#         try:
#             with open(self.filename, 'r') as file:
#                 self.content = unicode(file.read())
#         except IOError as e:
#             log.error(e)
#             self.content = u''
#             #Initialize all params from default values.
#             for key in self.params:
#                 self[key] = self[key]
# 
#     def commit(self):
#         if not os.path.isfile(self.filename):
#             dir = os.path.dirname(self.filename)
#             try:
#                 os.makedirs(dir)
#             except OSError as e:
#                 if e.errno != errno.EEXIST:
#                     raise e
#         with open(self.filename, 'w+') as file:
#             #Fix all linebreaks
#             file.write(os.linesep.join(self.content.splitlines()))
# 
#     def add_param(self, key, handler):
#         self.params[key] = handler
# 
#     def __iter__(self):
#         return self.params.__iter__()
# 
#     def __len__(self):
#         return len(self.params)
# 
#     def __getitem__(self, key):
#         return self.params[key].read(self.content)
# 
#     def __setitem__(self, key, value):
#         self.content = self.params[key].write(self.content, value)
# 
#     def keys(self):
#         return self.params.keys()
# 
#     def __delitem__(self, key):
#         del self.params[key]
# 
# def php_inserter(content, value):
#     match = PHP_BLOCKS.search(content)
#     if match:
#         content = PHP_BLOCKS.sub(
#             '<?php\g<1>\n%s\n?>' % (value), content)
#     else:
#         if content:
#             content += os.linesep
#         content += '<?php\n%s\n?>' % (value)
#     return content


from wtforms import Form
from wtforms.fields import (
    TextField, IntegerField, PasswordField, TextAreaField, HiddenField, Field)
from wtforms.widgets import PasswordInput, TextArea
from wtforms.validators import Optional, NumberRange
from yubiadmin.util.config import RegexHandler, FileConfig, php_inserter
        self.legend = legend
        self.description = description
        if lang:
            self.attrs['content']['ace-mode'] = lang
        super(FileForm, self).__init__(*args, **kwargs)
        self.content.label.text = 'File: %s' % filename


class DBConfigForm(ConfigForm):
    """
    Complete form for editing a dbconfig-common generated for PHP.
    """
    legend = 'Database'
    description = 'Settings for connecting to the database.'
    dbtype = TextField('Database type')
    dbserver = TextField('Host')
    dbport = IntegerField('Port', [Optional(), NumberRange(1, 65535)])
    dbname = TextField('Database name')
    dbuser = TextField('Username')
    dbpass = PasswordField('Password',
                           widget=PasswordInput(hide_value=False))

    def db_handler(self, varname, default):
        pattern = r'\$%s=\'(.*)\';' % varname
        writer = lambda x: '$%s=\'%s\';' % (varname, x)
        return RegexHandler(pattern, writer, inserter=php_inserter,
                            default=default)

    def __init__(self, filename, *args, **kwargs):
        if not self.config:

# Path: yubiadmin/util/config.py
# class RegexHandler(object):
#     def __init__(self, pattern, writer, reader=lambda x: x.group(1),
#                  inserter=lambda x, y: '%s\n%s' % (x, y),
#                  default=None):
#         self.pattern = re.compile(pattern)
#         self.writer = writer
#         self.reader = reader
#         self.inserter = inserter
#         self.default = default
# 
#     def read(self, content):
#         match = self.pattern.search(content)
#         if match:
#             return self.reader(match)
#         return self.default
# 
#     def write(self, content, value):
#         if value is None:
#             value = ''
#         if self.pattern.search(content):
#             new_content = self.pattern.sub(self.writer(value), content, 1)
#             if self.read(content) == self.read(new_content):
#                 #Value remains unchanged, don't re-write it.
#                 return content
#             else:
#                 return new_content
#         else:
#             return self.inserter(content, self.writer(value))
# 
# class FileConfig(MutableMapping):
#     """
#     Maps key-value pairs to a backing config file.
#     You can manually edit the file by modifying self.content.
#     """
#     def __init__(self, filename, params=[]):
#         self.filename = filename
#         self.params = OrderedDict()
#         for param in params:
#             self.add_param(*param)
# 
#     def read(self):
#         try:
#             with open(self.filename, 'r') as file:
#                 self.content = unicode(file.read())
#         except IOError as e:
#             log.error(e)
#             self.content = u''
#             #Initialize all params from default values.
#             for key in self.params:
#                 self[key] = self[key]
# 
#     def commit(self):
#         if not os.path.isfile(self.filename):
#             dir = os.path.dirname(self.filename)
#             try:
#                 os.makedirs(dir)
#             except OSError as e:
#                 if e.errno != errno.EEXIST:
#                     raise e
#         with open(self.filename, 'w+') as file:
#             #Fix all linebreaks
#             file.write(os.linesep.join(self.content.splitlines()))
# 
#     def add_param(self, key, handler):
#         self.params[key] = handler
# 
#     def __iter__(self):
#         return self.params.__iter__()
# 
#     def __len__(self):
#         return len(self.params)
# 
#     def __getitem__(self, key):
#         return self.params[key].read(self.content)
# 
#     def __setitem__(self, key, value):
#         self.content = self.params[key].write(self.content, value)
# 
#     def keys(self):
#         return self.params.keys()
# 
#     def __delitem__(self, key):
#         del self.params[key]
# 
# def php_inserter(content, value):
#     match = PHP_BLOCKS.search(content)
#     if match:
#         content = PHP_BLOCKS.sub(
#             '<?php\g<1>\n%s\n?>' % (value), content)
#     else:
#         if content:
#             content += os.linesep
#         content += '<?php\n%s\n?>' % (value)
#     return content


# Path: yubiadmin/util/form.py
from wtforms import Form
from wtforms.fields import (
    TextField, IntegerField, PasswordField, TextAreaField, HiddenField, Field)
from wtforms.widgets import PasswordInput, TextArea
from wtforms.validators import Optional, NumberRange
from yubiadmin.util.config import RegexHandler, FileConfig, php_inserter

        self.legend = legend
        self.description = description
        if lang:
            self.attrs['content']['ace-mode'] = lang
        super(FileForm, self).__init__(*args, **kwargs)
        self.content.label.text = 'File: %s' % filename


class DBConfigForm(ConfigForm):
    """
    Complete form for editing a dbconfig-common generated for PHP.
    """
    legend = 'Database'
    description = 'Settings for connecting to the database.'
    dbtype = TextField('Database type')
    dbserver = TextField('Host')
    dbport = IntegerField('Port', [Optional(), NumberRange(1, 65535)])
    dbname = TextField('Database name')
    dbuser = TextField('Username')
    dbpass = PasswordField('Password',
                           widget=PasswordInput(hide_value=False))

    def db_handler(self, varname, default):
        pattern = r'\$%s=\'(.*)\';' % varname
        writer = lambda x: '$%s=\'%s\';' % (varname, x)
        return RegexHandler(pattern, writer, inserter=php_inserter,
                            default=default)

    def __init__(self, filename, *args, **kwargs):
        if not self.config:

            self.config = FileConfig(