#!/usr/bin/python2

from edge.com import fs
import os


UI_ZABBIX_JNODE_PATH = '/etc/edge/setupstore/admin/actions/zabbix.json'
UI_ZABBIX_SCHEMA_PATH = '/etc/edge/setupstore/schemas/zabbix.json'


def _main():
    # if jnode dont exist - nothing to migrate
    if not os.path.exists(UI_ZABBIX_JNODE_PATH):
        return

    # update schema
    fs.ln_schema(UI_ZABBIX_SCHEMA_PATH, UI_ZABBIX_JNODE_PATH)

    # update jnode
    uiconf = fs.load_json3(UI_ZABBIX_JNODE_PATH)
    uiconf_pub = uiconf['rw']
    uiconf_conf = uiconf_pub.get('conf')
    if uiconf_conf is not None:
        # if jnode has 'conf' key nothing to migrate
        return

    enabled = uiconf_pub.get('enabled', False)
    new_uiconf_pub = {
        'internal': True,
        'role': 'service',
        'type': 'zabbix-agent',
        'conf': {
            'enabled': enabled
        }
    }

    if enabled:
        new_uiconf_pub['conf']['agent-port'] = uiconf_pub.get('agent-port', 10050)
        new_uiconf_pub['conf']['agent-host'] = uiconf_pub.get('agent-host', '')
        new_uiconf_pub['conf']['servers'] = uiconf_pub.get('servers', [])

    uiconf['rw'] = new_uiconf_pub
    fs.write_json_file(uiconf, UI_ZABBIX_JNODE_PATH, pretty=True)


if __name__ == '__main__':
    _main()
