#!/usr/bin/python
#
# arch-tag: d724cbf3-1d0c-4977-816f-58bcb6536951
#
# PMACS server configuration file reader
#
import sys
import os
try:
    from ConfigParser import RawConfigParser as cfgParser
except ImportError:
    from ConfigParser import ConfigParser as cfgParser
from ConfigParser import NoOptionError, NoSectionError

__version__ = '1.1'

class ConfigFile(cfgParser):
    _def = {'root' : '/var/lib/pmacs',
            'statedb' : 'ops_db/svcstate',
            'iospecdb' : 'ops_db/iospec',
            'archivedir' : 'archive',
            'passfile' : 'passwords.txt',
            'loadfile' : 'loadauth.txt',
            'calfile' : '',
            'interval' : '1',
            'checkauth' : 'off',
            'userrdb' : 'on',
            'npc' : 'mars-npc1',
            'psc' : 'mars-psc',
            'soapport' : '8080' }
    
    def __init__(self, file=None):
        cfgParser.__init__(self, self._def)
        if file:
            self.read(file)
        names = ('statedb', 'iospecdb', 'archivedir', 'passfile',
                 'loadfile', 'calfile')
        self.__dict__['root'] = self._tryget('dbase', 'root')
        for name in names:
            self.__dict__[name] = os.path.join(self.root, self._tryget('dbase', name))
        # User cannot override the default calibration file name
        self.defcalfile = os.path.join(self.root, 'defcal.csv')
        self.__dict__['npc'] = self._tryget('network', 'npc')
        self.__dict__['psc'] = self._tryget('network', 'psc')        
        self.__dict__['interval'] = int(self._tryget('network', 'interval'))
        self.__dict__['soapport'] = int(self._tryget('network', 'soapport'))
        self.__dict__['checkauth'] = self._tryget('network', 'checkauth') in ('1', 'on',
                                                                              'yes', 'true')
        self.__dict__['userrdb'] = self._tryget('dbase', 'userrdb') in ('1', 'on',
                                                                        'yes', 'true')
        
    def _tryget(self, section, option):
        try:
            return self.get(section, option)
        except (NoOptionError, NoSectionError):
            return self.defaults()[option]
        
        
