import os
import json
import subprocess

from django.utils.translation import ugettext as _

from freenasUI.failover.models import Failover
from freenasUI.failover.enc_helper import LocalEscrowCtl
from freenasUI.middleware.notifier import notifier
from freenasUI.system.alert import alertPlugins, Alert, BaseAlert

FAILOVER_JSON = '/tmp/failover.json'

class FailoverCheckAlert(BaseAlert):

    def run(self):

        status = notifier().failover_status()
        alerts = []

        fobj = None
        try:
            with open(FAILOVER_JSON, 'r') as f:
                fobj = json.loads(f.read())
        except:
            pass

        if status == 'ERROR':
            errmsg = None
            if os.path.exists('/tmp/.failover_failed'):
                with open('/tmp/.failover_failed', 'r') as fh:
                    errmsg = fh.read()
            if errmsg:
                errmsg = _("Failover failed: %s") % errmsg
            else:
                errmsg = _("Failover failed")
            alerts.append(Alert(
                Alert.CRIT,
                errmsg,
            ))
        elif status not in ('MASTER', 'BACKUP', 'SINGLE'):
            alerts.append(Alert(
                Alert.WARN, _(
                    'Could not determine external failover link status, check '
                    'cabling.'
                ),
            ))
        p1 = subprocess.Popen(
            ["/sbin/ifconfig", "carp1"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )
        stdout = p1.communicate()[0]
        if stdout.find("carp: INIT") != -1:
            alerts.append(Alert(
                Alert.CRIT, _(
                    'Could not determine internal failover link status, '
                    'Automatic failover disabled.'
                ),
            ))

        if status == 'MASTER':
            masters, backups = notifier().get_carp_states()
            if len(backups) > 0:
                alerts.append(Alert(
                    Alert.WARN,
                    _('Check external failover links.'),
                ))

        if status == 'MASTER':
            try:
                failover = Failover.objects.order_by('-id')[0]
                parse = notifier().zpool_parse(failover.volume.vol_name)
                if parse is None:
                    raise ValueError
            except:
                alerts.append(Alert(
                    Alert.CRIT,
                    _('Volume could not be imported in active head')
                ))

        if status == 'BACKUP':
            try:
                if len(fobj['phrasedvolumes']) > 0:
                    escrowctl = LocalEscrowCtl()
                    if not escrowctl.status():
                        alerts.append(Alert(
                            Alert.CRIT, _(
                                'No escrowed passphrase for failover. '
                                'Automatic failover disabled.'
                            ),
                        ))
                        # Kick a syncfrompeer if we don't.
                        os.system("/usr/local/bin/python /usr/local/www/freenasUI/failover/enc_helper.py syncfrompeer")
            except:
                pass
        return alerts

alertPlugins.register(FailoverCheckAlert)
