#!/usr/bin/python

from edge.com import fs
from edge.webserver.sysconf.dgconf.blobstore import BsDgconfEditor65535
from edge.webserver.sysconf.dgconf.setupstore import SsDgconf

_BASE_SPOOL_PATH = '/var/spool/edge/bs-cache'
_BASE_ARCH_PATH = '/etc/edge/setupstore/admin/actions/eventstore'


def _main():
    bs_dgconf = BsDgconfEditor65535.load()
    ss_dgconf = SsDgconf.load_conf()
    ss_groups = ss_dgconf['groups']

    ss_sys_group = filter(lambda x: x['name'] == 'system', ss_groups)[0]  # type: dict
    ss_sys_modules = ss_sys_group['modules']

    # remove bs.65535 from system group
    ss_sys_group['modules'] = filter(lambda m: 'blobstore' not in m, ss_sys_modules)
    ss_sys_group['spool-size'] = 10  # change system spool size

    # add store group for bs.65535 if not exist
    ss_bscache_group = filter(lambda x: x['name'] == 'bs-cache', ss_groups)
    if len(ss_bscache_group) == 0:
        bs_chan_count = bs_dgconf.chan_count
        ss_groups.append({
            'name': 'bs-cache',
            'spool-size': 50 * bs_chan_count,
            'modules': ['/etc/edge/blobstore.65535/']
        })

    SsDgconf.save_conf(ss_dgconf)

    storage = bs_dgconf.jnode['storage']
    for chan_info in storage:
        chan_cache = chan_info['cache']
        chan_cache['directory'] = fs.join_path(_BASE_SPOOL_PATH, 'bs65535-bs65535-store')

        chan_cache_limits = chan_cache['limits']
        if chan_cache_limits['max-abs-time'] < 60:
            chan_cache_limits['max-abs-time'] = chan_cache_limits['max-abs-time'] * 60

        chan_arch = chan_info['archive']
        if chan_arch['filesize'] < 1024:
            chan_arch['filesize'] = chan_arch['filesize'] * 1024

        es_uiconf = fs.load_json3(fs.join_path(_BASE_ARCH_PATH, chan_info['channel'], '0.json'))
        es_uiconf_pub = es_uiconf['rw']  # type: dict
        es_uiconf_args = es_uiconf_pub['args']

        if chan_arch['limits'].get('max-abs-time'):
            chan_arch['limits']['max-abs-time'] = es_uiconf_args['cleanup']['max-abs-time'][1] * 60

        if chan_arch['limits'].get('max-rel-time'):
            chan_arch['limits']['max-rel-time'] = es_uiconf_args['cleanup']['max-rel-time'][1] * 60

    bs_dgconf.save()


if __name__ == '__main__':
    _main()
