#!/usr/bin/python
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
    jnode = fs.load_json(UI_ZABBIX_JNODE_PATH)
    jnode_pub = jnode['rw']
    jnode_conf = jnode_pub.get('conf')
    # if jnode has 'conf' key nothing to migrate
    if jnode_conf is not None:
        return

    enabled = jnode_pub.get('enabled', False)
    new_rw_jnode = {
        'internal': True,
        'role': 'service',
        'type': 'zabbix-agent',
        'conf': {
            'enabled': enabled
        }
    }
    if enabled:
        new_rw_jnode['conf']['agent-port'] = jnode_pub.get('agent-port', 10050)
        new_rw_jnode['conf']['agent-host'] = jnode_pub.get('agent-host', '')
        new_rw_jnode['conf']['servers'] = jnode_pub.get('servers', [])

    jnode['rw'] = new_rw_jnode
    fs.write_json_file(jnode, UI_ZABBIX_JNODE_PATH, True)

if __name__ == '__main__':
    main()
