#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu

from __future__ import (unicode_literals, absolute_import,
                        division, print_function)
import sys
import os

from rapidpro_controller import get_logger, run_command
from rapidpro_controller.cluster import (was_ip_master, is_ip_master,
                                         get_ip_master, cache_ip_master)

logger = get_logger(os.path.basename(__file__))


def main():
    was_master = was_ip_master()
    is_master = is_ip_master()

    # no change, exit
    if was_master == is_master:
        return 0

    # writting new status to disk
    cache_ip_master(get_ip_master())

    if is_ip_master:
        logger.info("[CLUSTER-IP] detected we are now MASTER")
        return run_command(['rapidpro-record-ipmaster'])
    else:
        logger.info("[CLUSTER-IP] detected we are now SLAVE")
        return run_command(['rapidpro-record-ipslave'])


if __name__ == '__main__':
    sys.exit(main())
