#!/usr/bin/python
from edge.com import fs
from edge import path_helpers as ph
from os.path import join as join_path
import ujson

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

ss_jnode = fs.load_json(ph.SETUPSTORE_CONF_FILEPATH)
groups_jnode = ss_jnode['groups']

system_group = filter(lambda group_jnode: group_jnode['name'] == 'system', groups_jnode)[0]
system_modules = system_group['modules']

# remove bs.65535 from system group
new_system_modules = filter(lambda module: 'blobstore' not in module, system_modules)
system_group['modules'] = new_system_modules
# change system spool size
system_group['spool-size'] = 10

# add store group for bs.65535 if not exist
store_groups = filter(lambda group_jnode: group_jnode['name'] == 'bs-cache', groups_jnode)

bs_jnode = fs.load_json(ph.BLOBSTORE_CONF_FILEPATH)
bs_ch_count = len(bs_jnode['storage'])

if len(store_groups) == 0:
    store_jnode = {
        'modules': ['/etc/edge/blobstore.65535/'],
        'name': 'bs-cache',
        'spool-size': 50 * bs_ch_count
    }

    groups_jnode.append(store_jnode)

with open(ph.SETUPSTORE_CONF_FILEPATH, 'w') as json_file:
    ujson.dump(ss_jnode, json_file, indent=2)

storage = bs_jnode["storage"]
for channel in storage:
    channel['cache']['directory'] = join_path(_BASE_SPOOL_PATH, "bs65535-bs65535-store")
    if channel['cache']['limits']['max-abs-time'] < 60:
        channel['cache']['limits']['max-abs-time'] = channel['cache']['limits']['max-abs-time'] * 60

    if channel['archive']['filesize'] < 1024:
        channel['archive']['filesize'] = channel['archive']['filesize'] * 1024

    archive_config = fs.load_json(join_path(_BASE_ARCH_PATH, channel['channel'], '0.json'))
    arch_args = archive_config['rw']['args']

    if channel['archive']['limits'].get('max-abs-time'):
        channel['archive']['limits']['max-abs-time'] = arch_args['cleanup']['max-abs-time'][1] * 60

    if channel['archive']['limits'].get('max-rel-time'):
        channel['archive']['limits']['max-rel-time'] = arch_args['cleanup']['max-rel-time'][1] * 60

with open(ph.BLOBSTORE_CONF_FILEPATH, 'w') as json_file:
        ujson.dump(bs_jnode, json_file, indent=2)




