# Copyright (c) 2015 iXsystems, Inc.
# All rights reserved.
# This file is a part of TrueNAS
# and may not be copied and/or distributed
# without the express permission of iXsystems.

import logging
import os
import re
import subprocess
from freenasUI.middleware.client import client

log = logging.getLogger('truenas.notifier')


class TNNotifier(object):

    def is_freenas(self):
        return False

    def set_global_alarm(self, value):
        cmd = "/usr/local/sbin/dmidecode -s baseboard-manufacturer"
        p1 = self._pipeopen(cmd, logger=None)
        motherboard = p1.communicate()[0].split('\n', 1)[0].strip()
        if motherboard == "GIGABYTE":
            try:
                with open('/dev/cuau1', 'w') as f:
                    if value == 'OK':
                        f.write('1')
                    else:
                        f.write('f')
            except IOError as e:
                log.debug('Failed to set global alarm: %s', e)
                return False
            finally:
                return True
        elif motherboard == "Celestica":
            try:
                enclosures = ["/dev/" + enc for enc in os.listdir("/dev") if enc.startswith("ses")]
                for enclosure in enclosures:
                    proc = subprocess.Popen([
                        '/usr/sbin/getencstat',
                        '-V', enclosure,
                    ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf8')
                    encstat = proc.communicate()[0].strip()
                    if not re.search("Enclosure Name: CELESTIC (P3215-O|P3217-B)", encstat, re.M):
                        continue;
                    proc = subprocess.Popen([
                        '/usr/sbin/setobjstat', enclosure,
                        '0x3f', '0x80', '0', '0', ('0' if value == 'OK' else '0x02')
                    ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf8')
                    proc.communicate()
            except IOError as e:
                log.debug('Failed to set global alarm: %s', e)
                return False
            finally:
                return True

    def get_chassis_hardware(self):
        with client as c:
            return c.call('truenas.get_chassis_hardware')
