#!/usr/bin/python2

import json
from shutil import copy as shutil_copy
import os.path

_NTP_CONF_PATH = '/etc/ntp.conf'
_NTP_CONF_BAK_PATH = '/etc/ntp.conf.bak'
_UI_TIME_JNODE_PATH = '/etc/edge/setupstore/admin/actions/time.json'
_UI_TIME_DEFJNODE_PATH = '/opt/edge/share/setupstore/ui/time-jnode.json'


def _edit_ntp_conf(ui_ro_jnode, ui_rw_jnode):
    """
    :type ui_ro_jnode: dict
    :type ui_rw_jnode: dict
    """
    ntp_conf = []

    time_mode = ui_rw_jnode['mode']
    if time_mode == 'ntp':
        servers_jnode = ui_rw_jnode['servers']
        for server_jnode in servers_jnode:
            if server_jnode['prefered']:
                ntp_conf.append('pool %s prefer\n' % server_jnode['address'])
            else:
                ntp_conf.append('pool %s\n' % server_jnode['address'])

        for server_jnode in servers_jnode:
            ntp_conf.append('restrict %s noquery notrap\n' % server_jnode['address'])

        footer_lines = '\n'.join(ui_ro_jnode.get('ntp-conf-footer', []))
        ntp_conf.append(footer_lines)

    elif time_mode == 'manual':
        pass

    else:
        raise NotImplementedError

    with open(_NTP_CONF_PATH, 'w') as new_ntp_file:
        new_ntp_file.write(''.join(ntp_conf))


def _main():
    if not os.path.exists(_UI_TIME_JNODE_PATH):
        print 'nothing to do: skip %s' % _UI_TIME_JNODE_PATH
        return

    shutil_copy(_NTP_CONF_PATH, _NTP_CONF_BAK_PATH)
    print 'done: backup %s to %s' % (_NTP_CONF_PATH, _NTP_CONF_BAK_PATH)

    with open(_UI_TIME_JNODE_PATH, 'r') as json_file:
        try:
            ui_jnode = json.load(json_file)
        except ValueError:
            print 'nothing to do: skip %s' % _UI_TIME_JNODE_PATH
            return

    if not ui_jnode['ro'].get('ntp-conf-footer', None):
        with open(_UI_TIME_DEFJNODE_PATH) as def_jnode_file:
            def_ui_jnode = json.load(def_jnode_file)
        ui_jnode['ro']['ntp-conf-footer'] = def_ui_jnode['ro']['ntp-conf-footer']

    with open(_UI_TIME_JNODE_PATH, 'w') as json_file:
        json.dump(ui_jnode, json_file, indent=2)
    print 'done: edit %s' % _UI_TIME_JNODE_PATH

    _edit_ntp_conf(ui_jnode['ro'], ui_jnode['rw'])
    print 'done: edit %s' % _NTP_CONF_PATH


if __name__ == '__main__':
    _main()
