#!/usr/bin/python
"""Tool to add/remove/rescan/get info about fibrechannel LUNs on a server"""

import fcntl
import io
import json
import optparse
import os
import platform
import pwd
import re
import signal
import struct
import sys
import termios
import textwrap
from abc import ABCMeta, abstractmethod
from optparse import SUPPRESS_HELP, IndentedHelpFormatter, OptionGroup
from time import sleep

from rs_block_storage.helpers import CommandNotFoundError, CommandPermissionError, cmd_exists
from rs_block_storage.helpers.config import config
from rs_block_storage.helpers.log import customize_logger, logger
from rs_block_storage.helpers.rexit import RExit
from rs_block_storage.rbs import get_log_level
from rs_block_storage.server.server import Server
from rs_block_storage.version import __version__

# Time (in seconds) to sleep for after making changes
# or probing the scsi bus, to give any asynchronous
# processes time to complete
SETTLE_TIME = 1

# Directories that might contain Oracle ASM disk paths
ORA_DEV_DIRS = ["/dev/ora", "/dev/oracleasm/disks"]

# Python3 changed raw_input() to input()
# Put it back for Python2 compat
if platform.python_version_tuple()[0] == "3":
    raw_input = input


def confirm(question):
    """Ask for confirmation from the user"""
    answer = raw_input("%s (y/n): " % question).lower().strip()
    if answer == "y":
        return True
    if answer == "n":
        print("Operation aborted")
        return False
    logger.error("You must respond with 'y' or 'n'")
    return confirm(question)


def writefile(path, content):
    """Write content to file"""
    logger.debug("Writing '%s' to %s" % (content, path))
    with open(path, "w") as f:
        f.write(content)


def command_fail(cmd, stderr, stdout=None, retcode=RExit.ERR_CMD_FAIL):
    """Log failure of command and return error code"""
    if stdout:
        output = "\n  ".join([stdout, stderr])
    else:
        output = stderr
    logger.error("Error running command '%s':\n  %s" % (cmd, output))
    return retcode


def bytes_to_human(in_val):
    """Convert bytes to a human readable form"""
    suffixes = " KMGTPEZ"
    val = int(in_val)
    if val <= 1024:
        # small enough to just report the exact number of bytes
        return "%dB" % val
    si_val = val
    while val > 1024:
        # Keep dividing by 1024 until we get a number in a reasonable
        # range for the suffix
        # Also keep a tally of the SI version of the number
        val = val / 1024.0
        si_val = si_val / 1000.0
        suffixes = suffixes[1:]
    # Report both the SI & 1024^n values, to avoid any confusion
    return "%3.1f%sB / %3.1f%siB" % (si_val, suffixes[0:1], val, suffixes[0:1])


def bytes_to_gib(in_val):
    """Convert bytes to GiB"""
    return "%3.1f" % (in_val / 1073741824.0)  # 1024**3


def is_clustered():
    """Determine if clustered/shared LVM is being used"""
    (rc, stdout, stderr) = Server.run_command("pgrep 'clvmd|lvmlockd'")
    return bool(rc == 0)


def oracle_in_use():
    """Try and determine if Oracle DB is in use"""
    # Check for Oracle ASM devices first
    for ora_dir in ORA_DEV_DIRS:
        if os.path.isdir(ora_dir) and os.listdir(ora_dir):
            return True
    # Look for processes containing 'ora' or 'tnslsnr'
    pgrep_cmds = ["-f ora|tnslsnr"]
    # Also look for processes owned by a user called 'oracle' if that user exists
    try:
        pwd.getpwnam("oracle")
        pgrep_cmds.append("-u oracle")
    except KeyError:
        # Oracle user doesn't exist
        pass
    for cmd in ["pgrep %s" % c for c in pgrep_cmds]:
        rc, stdout, stderr = Server.run_command(cmd)
        if rc == 0:
            return True
        if rc != 1:
            command_fail(cmd, stderr)
    return False


class IndentedListFormatter(IndentedHelpFormatter):
    """
    Extends optparse.IndentedHelpFormatter to allow lists in help description
    for improved formatting ability
    """

    def __init__(self, *args, **kwargs):
        # Bash might not provide the COLUMNS environment variable to us
        # (it is a dynamic variable), and the super class will set the width
        # to 80 if that isn't present
        width = kwargs.get("width")
        if width is None:
            try:
                width = int(os.environ["COLUMNS"])
            except (KeyError, ValueError):
                try:
                    data = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, "1234")
                    _, width = struct.unpack("hh", data)
                except Exception:
                    width = 80
            kwargs["width"] = width
        # Doesn't inherit from object, so we can't use super()
        IndentedHelpFormatter.__init__(self, *args, **kwargs)

    def format_option(self, option):
        if not option.help or not isinstance(option.help, (list, tuple)):
            # Doesn't inherit from object, so we can't use super()
            return IndentedHelpFormatter.format_option(self, option)
        result = []
        opts = self.option_strings[option]
        opt_width = self.help_position - self.current_indent - 2
        if len(opts) > opt_width:
            opts = "%*s%s\n" % (self.current_indent, "", opts)
            indent_first = self.help_position
        else:  # start help on same line as opts
            opts = "%*s%-*s  " % (self.current_indent, "", opt_width, opts)
            indent_first = 0
        result.append(opts)
        if option.help:
            desc_lines = option.help
            help_lines = []
            for line in desc_lines:
                # Cheat, and set option.help to a single string
                # so expand_default works
                option.help = line
                help_text = self.expand_default(option)
                help_lines.extend(textwrap.wrap(help_text, self.help_width))
            result.append("%*s%s\n" % (indent_first, "", help_lines[0]))
            result.extend(["%*s%s\n" % (self.help_position, "", line) for line in help_lines[1:]])
            # Put the list back into option.help
            option.help = desc_lines
        elif opts[-1] != "\n":
            result.append("\n")
        return "".join(result)


class FCData(object):
    """Class to hold info about fibrechannel state"""

    HOST_DIR = "/sys/class/fc_host"
    TRANSPORT_DIR = "/sys/class/fc_transport"

    def __init__(self):
        self.fc_hosts = {}
        self.fc_targets = {}
        self.read_fc_data()

    def read_fc_data(self):
        self.read_fc_hosts()
        self.read_fc_targets()

    def read_fc_hosts(self):
        """Load data about the FC HBA connections"""
        self.fc_hosts = {}
        host_re = re.compile(r"host(\d+)")
        try:
            for host in os.listdir(self.HOST_DIR):
                # /sys/class/fc_host/hostN/port_state
                state_path = os.path.join(self.HOST_DIR, host, "port_state")
                mtch = host_re.match(host)
                if mtch and os.path.exists(state_path):
                    with open(state_path, "r") as f:
                        self.fc_hosts[mtch.group(1)] = f.read().strip()
        except IOError as e:
            logger.error("Error reading fc_host info:\n%s" % e)
            raise

    def read_fc_targets(self):
        """Load data about FC connections that have LUNs connected"""
        self.fc_targets = []
        tgt_re = re.compile(r"target(\d+):(\d+):(\d+)")
        try:
            for tgt in os.listdir(self.TRANSPORT_DIR):
                # /sys/class/fc_transport/targetH:B:T
                mtch = tgt_re.match(tgt)
                if mtch:
                    self.fc_targets.append(mtch.groups())
        except IOError as e:
            logger.error("Error reading fc_transport info:\n%s" % e)
            raise

    @property
    def active_hosts(self):
        """List of FC hosts that are online"""
        return [h for h, st in self.fc_hosts.items() if st.lower() == "online"]

    @property
    def transport_hosts(self):
        """List of FC hosts that have fc_transport entries"""
        return set([h[0] for h in self.fc_targets])


class LUNBase(object):
    """Base class for a single LUN"""

    __metaclass__ = ABCMeta
    _VENDORS = {"000097": "EMC", "006016": "EMC", "24a937": "PURE", "00a098": "NETAPP"}
    BLOCK_BASE = "/sys/class/block"

    def __init__(self):
        self.wwn = None
        self.paths = []
        self._mapping = None
        self.local_id = None
        self.local_id_name = None
        self._size = None
        self.sector_size = 512
        self._partitions = None
        self._dev_by_node = {}

    def partition_lun(self, options):
        """Create a single partition in a GPT partition table"""
        if self.partitions:
            logger.note("LUN is already partitioned, not creating new ones")
            return RExit.OK
        mktable_cmd = "parted -s %s mktable gpt" % self.mapping_path
        mkpart_cmd = "parted -s %s mkpart %s1 0%% 100%%" % (self.mapping_path, self.mapping)
        lvmtag_cmd = "parted -s %s set 1 lvm on" % self.mapping_path

        cmd_list = [mktable_cmd, mkpart_cmd]
        if not options.nolvmtag:
            cmd_list.append(lvmtag_cmd)
        for cmd in cmd_list:
            (rc, stdout, stderr) = Server.run_command(cmd)
            if rc != 0:
                return command_fail(cmd, stderr, retcode=RExit.ERR_PART_FAIL)

        if not self.partitions:
            # parted may have already triggered the kernel to re-read the
            # partition table, in which case we don't need to
            (rc, stdout, stderr) = Server.run_command(self.partprobe_cmd)
            if rc != 0:
                return command_fail(self.partprobe_cmd, stderr, retcode=RExit.ERR_PART_FAIL)
            if not self.partitions:
                logger.error("Can't detect partitions after creating them")
                return RExit.ERR_PART_FAIL
        return RExit.OK

    def pvcreate(self, partition=1):
        """Create a physical volume on the first partition"""
        if not self.partitions:
            return RExit.ERR_PART_FAIL
        cmd = "pvcreate --metadatasize=250k %s" % self.partitions[partition - 1]
        (rc, stdout, stderr) = Server.run_command(cmd)
        if rc != 0:
            return command_fail(cmd, stderr, retcode=RExit.ERR_LVM_PV)
        return RExit.OK

    def rescan_paths(self):
        """Rescan all of the sub-paths of the LUN, to pick up size changes"""
        for path in self.paths:
            # /sys/class/block/sdX/device/rescan
            writefile(os.path.join(self.BLOCK_BASE, path, "device", "rescan"), "1")
        self._size = None
        sleep(SETTLE_TIME)
        return RExit.OK

    def delete_paths(self):
        """Delete all of the sub-paths of the LUN, to finish removing it"""
        for path in self.paths:
            # /sys/class/block/sdX/device/delete
            writefile(os.path.join(self.BLOCK_BASE, path, "device", "delete"), "1")
        self.paths = []
        sleep(SETTLE_TIME)
        return RExit.OK

    def pv_check(self):
        """Return list of PVs associated with the LUN & its partitions"""
        pvs_in_use = []
        for pv in self.partitions + [self.mapping_path]:
            (rc, stdout, stderr) = Server.run_command(
                "pvs -o attr --noheadings --readonly --ignorelockingfailure %s" % pv
            )
            if rc == 0:  # We found some sort of PV
                pvbits = stdout.strip()
                # EL6 4 bits: (a)llocatable, e(x)ported, (m)issing, (u)sed
                # EL7 3 bits: (d)uplicate/(a)llocatable/(u)sed, e(x)ported, (m)issing
                #  unused:   "--"
                #  in use:   "a-"
                #  exported: "ax"
                if pvbits[0] == "a" and pvbits[1] != "x":
                    logger.debug("PV %s is (a)llocatable but not e(x)ported: %s" % (pv, pvbits))
                    pvs_in_use.append("PV: %s" % pv)
        return pvs_in_use

    def standalone_mounted(self):
        """Return list of direct mounts of the LUN & its partitions"""
        mounts = []
        mount_list = self.partitions + [self.mapping_path]
        with open("/proc/self/mounts", "r") as f:
            for line in f:
                mnt = line.split()
                if mnt[0] in mount_list:
                    mounts.append("MOUNT: %s %s" % (mnt[0], mnt[1]))
        return mounts

    def oracleasm_used(self):
        """Return list of Oracle ASM disks associated with the LUN & its partitions"""
        asm = []
        for ora_dir in [d for d in ORA_DEV_DIRS if os.path.isdir(d)]:
            for ora_dev in os.listdir(ora_dir):
                ora_dev = os.path.join(ora_dir, ora_dev)
                st = os.stat(ora_dev)
                node = "%s:%s" % (os.major(st.st_rdev), os.minor(st.st_rdev))
                if node in self._dev_by_node:
                    asm.append("ASM: %s %s" % (self._dev_by_node[node], ora_dev))
        return asm

    def processes_used(self):
        """Return list of processes directly using the LUN or its partitions"""
        pids = []
        cmd = "fuser -m %s" % " ".join(self.partitions + [self.mapping_path])
        (rc, stdout, stderr) = Server.run_command(cmd)
        if rc == 0:
            # we found at least one process on at least one path
            # fuser "helpfully" writes paths to stderr and pids to stdout
            for path, plist in zip(stderr.splitlines(), stdout.splitlines()):
                pids.append("PID: %s %s" % (path.strip(), plist.strip()))
        elif stderr.strip():
            command_fail(cmd, stderr)
        return pids

    @abstractmethod
    def _read_partitions(self):
        """Returns dict of partition: dev_node (i.e. '/dev/part': 'major:minor')"""
        pass

    def remove(self):
        """Run tasks to remove the LUN"""
        return self.delete_paths()

    @property
    def mapping(self):
        """Name of the LUN as used by the system (no path)"""
        return self._mapping

    @mapping.setter
    def mapping(self, value):
        self._mapping = value
        # /sys/class/block/<dev_name>/dev - contains major:minor device ID
        dev_path = os.path.join(self.BLOCK_BASE, value, "dev")
        if os.path.exists(dev_path):
            with open(dev_path, "r") as f:
                self._dev_by_node[f.read().strip()] = self.mapping_path

    @property
    def vendor(self):
        """Vendor of the SAN the LUN is supplied from"""
        if not self.wwn or len(self.wwn) < 32:
            return None
        return self._VENDORS.get(self.wwn[1:7].lower())

    @property
    def size(self):
        """Size of the LUN in bytes"""
        if not self._size:
            # /sys/class/block/<dev_name>/size - contains device size in sectors
            spath = os.path.join(self.BLOCK_BASE, self.mapping, "size")
            if os.path.exists(spath):
                with open(spath, "r") as f:
                    self._size = f.read().strip()
            # SSDs may have a different sector size, so read what the device
            # tells us it is, just in case
            # /sys/class/block/<dev_name>/queue/hw_sector_size
            hpath = os.path.join(self.BLOCK_BASE, self.mapping, "queue", "hw_sector_size")
            if os.path.exists(hpath):
                try:
                    with open(hpath, "r") as f:
                        self.sector_size = int(f.read().strip())
                except Exception:
                    self.sector_size = 512
        return int(self._size) * self.sector_size

    @property
    def extra_print_info(self):
        """Additional info to print about the LUN"""
        if self.local_id != self.wwn:
            return "%s: %s" % (self.local_id_name, self.local_id)
        return ""

    @property
    def has_data(self):
        """Return True if the LUN appears to have any data on it"""
        # Say we already have data if any of the following are true:
        # Partitions already present
        if self.partitions:
            return True
        # blkid can tell us anything at all about the LUN
        cmd = "/sbin/blkid -p %s" % self.mapping_path
        (rc, stdout, stderr) = Server.run_command(cmd)
        if rc == 0 and stdout:
            # blkid found something
            return True
        # Any non-zero bytes are present in the first 16M
        with io.open(self.mapping_path, "rb") as f:
            # Read first 16M or entire LUN if it is smaller
            b = bytearray(min(self.size, 16 * 1024 * 1024))
            f.readinto(b)
            return any(b)

    @property
    def used(self):
        """ Return list of places the LUN is used"""
        return (
            self.pv_check()
            + self.standalone_mounted()
            + self.oracleasm_used()
            + self.processes_used()
        )

    @property
    @abstractmethod
    def mapping_path(self):
        """Full path to refer to the LUN by (under /dev)"""
        pass

    @property
    @abstractmethod
    def partprobe_cmd(self):
        """Command to re-read the partition table for the kernel"""
        pass

    @property
    def partitions(self):
        """List of partitions attached to the LUN (full paths under /dev)"""
        if not self._partitions:
            part_map = self._read_partitions()
            self._partitions = list(part_map.keys())
            for part, dev in part_map.items():
                if dev:
                    self._dev_by_node[dev] = part
        return self._partitions


class LUNCollection(object):
    """Base class for a collection of LUNs"""

    __metaclass__ = ABCMeta

    def __init__(self, fc_data=None):
        self.fc_data = fc_data or FCData()
        self._luns = {}
        self.read_luns()

    @abstractmethod
    def _read_luns(self):
        """Subclass specific method to populate the LUN information"""
        pass

    @abstractmethod
    def post_scan(self):
        """Actions to take following scanning for new LUNs"""
        pass

    @abstractmethod
    def post_removal(self):
        """Actions to take after removing a LUN"""
        pass

    def read_luns(self):
        """Populate LUN information"""
        # Force re-read of FC info
        self.fc_data.read_fc_data()
        if not self.fc_data.transport_hosts:
            # if no data here, we have no LUNs at all
            # and can give up straight away
            return
        self._read_luns()

    def format_lunid(self, lunid):
        """Coerce the LUN ID we were given into a standard format"""
        new_lunid = lunid
        # A WWN should be 32 hex characters
        # The Linux kernel creates scsi IDs by prepending
        # a 3 to the WWN - so remove that character
        # if we were passed such a thing
        if len(new_lunid) > 32 and lunid.startswith("3"):
            lunid = new_lunid[1:]

        new_lunid = re.sub("[^A-Za-z0-9]+", "", new_lunid)
        # Only return the formatted LUN ID if it ended up as 32 chars
        # Otherwise it probably wasn't a WWN, so we should leave it alone
        if len(new_lunid) == 32:
            return new_lunid
        return lunid

    @staticmethod
    def factory():
        """Return the appropriate LUN collection type based on software on the device"""
        if cmd_exists(EMCCollection.PMT_CMD):
            logger.debug("%s detected, using PowerPath logic" % EMCCollection.PMT_CMD)
            return EMCCollection()
        logger.debug("%s not detected - checking for DM-MPIO instead" % EMCCollection.PMT_CMD)
        if cmd_exists(MpathCollection.MPIO_CMD):
            logger.debug("%s detected, using DM-MPIO logic" % MpathCollection.MPIO_CMD)
            return MpathCollection()
        logger.fatal("Can't find %s or %s" % (EMCCollection.PMT_CMD, MpathCollection.MPIO_CMD))
        sys.exit(RExit.ERR_GENERAL)

    def get_lun(self, lunid):
        """Get details of a single LUN if it exists"""
        return self._luns.get(lunid, None)

    def lun_exists(self, lunid):
        """Determine if the supplied LUN ID is already visible on the server"""
        return bool(self.get_lun(lunid))

    def _add_entry(self, entry):
        """Call from read_luns() to add a new LUN entry"""
        # All LUNs can be looked up by WWN
        if entry.wwn:
            self._luns[entry.wwn.lower()] = entry

    @property
    def luns(self):
        """List of the LUNs on the server"""
        # Cast to list as Python3 dict gives you a dictview
        # which will update as the dictionary is updated
        return list(self._luns.values())

    @property
    def lunids(self):
        """List of the IDs (WWNs) of LUNs on the server"""
        # Cast to set as Python3 dict gives you a dictview
        # which will update as the dictionary is updated
        return set(self._luns.keys())


class EMCCollection(LUNCollection):
    """Collection of EMC/PowerPath based LUNs"""

    PMT_CMD = "/sbin/powermt"

    class EMCLun(LUNBase):
        """Specific class for an EMC/PowerPath LUN"""

        def __init__(self):
            super(EMCCollection.EMCLun, self).__init__()
            self.local_id_name = "LUN ID"

        def _read_partitions(self):
            # Partitions appear as directories under /sys/class/block/emcpowerX
            # Partition directory names are emcpowerXn
            root_path = os.path.join(self.BLOCK_BASE, self.mapping)
            part_list = [e for e in os.listdir(root_path) if e.startswith(self.mapping)]
            part_map = {}
            for part in part_list:
                dev = None
                # /sys/class/block/emcpowerXn/dev holds the major:minor value
                dev_path = os.path.join(self.BLOCK_BASE, part, "dev")
                if os.path.exists(dev_path):
                    with open(dev_path, "r") as f:
                        dev = f.read().strip()
                part_map[os.path.join("/dev", part)] = dev
            return part_map

        def remove(self):
            cmd = "%s remove dev=%s" % (EMCCollection.PMT_CMD, self.mapping)
            (rc, stdout, stderr) = Server.run_command(cmd)
            if rc != 0:
                return command_fail(cmd, stderr)
            sleep(SETTLE_TIME)
            return super(EMCCollection.EMCLun, self).remove()

        @property
        def vendor(self):
            v = super(EMCCollection.EMCLun, self).vendor
            if not v:
                # Assume it is an EMC LUN then anyway
                v = "EMC"
            return v

        @property
        def mapping_path(self):
            # Pseudo device names appear directly in /dev
            return os.path.join("/dev", self.mapping)

        @property
        def partprobe_cmd(self):
            return "partx -a %s" % self.mapping_path

    def __init__(self):
        self.luns_by_emc_lunid = {}
        self.luns_by_emc_pseudo = {}
        super(EMCCollection, self).__init__()

    def _add_entry(self, entry):
        super(EMCCollection, self)._add_entry(entry)
        # Also allow lookup by EMC Logical ID, and Pseudo device name
        if entry.local_id:
            self.luns_by_emc_lunid[self.format_lunid(entry.local_id).lower()] = entry
        if entry.mapping:
            self.luns_by_emc_pseudo[entry.mapping.lower()] = entry

    def _read_luns(self):
        cmd = "%s display dev=all" % self.PMT_CMD
        drivers = ["lpfc", "bfa", "qla2xxx"]

        lunentry = EMCCollection.EMCLun()

        (rc, stdout, stderr) = Server.run_command(cmd)
        if rc != 0:
            command_fail(cmd, stderr)
            return
        for entry in stdout.splitlines():
            entry = entry.strip()
            if not entry or entry.startswith(("#", "=", "-")):
                # blank or formatting lines
                continue
            vals = [v for v in entry.split() if v]
            if len(vals) > 8 and any(x in vals for x in drivers):
                # A sub-path entry - we only care about the device name here
                lunentry.paths.append(vals[2])
            else:
                if vals[0] == "Pseudo":
                    # This should be the start of a new LUN, so record
                    # anything we already have
                    self._add_entry(lunentry)
                    lunentry = EMCCollection.EMCLun()
                    lunentry.mapping = vals[1].split("=")[1]
                if vals[0] == "Logical":
                    # Could be either a 4/5/8 character EMC LUN ID
                    # or a 32 character WWN
                    lun = vals[2].split("=")[1]
                    lunentry.local_id = lun
                    lunentry.local_id_name = "LUN ID"
                    if len(lun) > 8 or not lunentry.wwn:
                        # Either this is definitely a WWN
                        # or we haven't seen one yet, so record the
                        # EMC LUN ID as the WWN in case we don't get one later
                        lunentry.wwn = lun
                if vals[0] == "Device":
                    lunentry.wwn = vals[1].split("=")[1]
        # Ensure the final lun entry is recorded
        self._add_entry(lunentry)

    def format_lunid(self, lunid):
        mtch = re.match(r"(?:/?dev/)?(emcpower.*)", lunid)
        if mtch:
            # Pseudo device name
            lunid = mtch.group(1)
        elif len(lunid) in [4, 5, 8]:
            # EMC Logical device ID - coerce to 8 character version
            while len(lunid) < 8:
                lunid = "0" + lunid
        else:
            lunid = super(EMCCollection, self).format_lunid(lunid)
        return lunid

    def get_lun(self, lunid):
        lunid = self.format_lunid(lunid).lower()
        # Try by WWN first
        lun = super(EMCCollection, self).get_lun(lunid)
        if not lun:
            if len(lunid) > 8:
                # emcpowerX
                lun = self.luns_by_emc_pseudo.get(lunid, None)
            else:
                # try EMC Logical Device ID
                lun = self.luns_by_emc_lunid.get(lunid, None)
        return lun

    def post_scan(self):
        # powermt config; powermt save
        for cmd in ["%s %s" % (self.PMT_CMD, c) for c in ["config", "save"]]:
            (rc, stdout, stderr) = Server.run_command(cmd)
            if rc != 0:
                return command_fail(cmd, stderr)
        sleep(SETTLE_TIME)
        self.read_luns()
        return RExit.OK

    def post_removal(self):
        for cmd in ["%s %s" % (self.PMT_CMD, c) for c in ["release", "save"]]:
            (rc, stdout, stderr) = Server.run_command(cmd)
            if rc != 0:
                return command_fail(cmd, stderr)
        return RExit.OK


class MpathCollection(LUNCollection):
    """Collection of dm-multipath base LUNs"""

    MPIO_CMD = "/sbin/multipathd"

    def __init__(self):
        self.luns_by_dm = {}
        self.luns_by_alias = {}
        super(MpathCollection, self).__init__()

    class MpathLUN(LUNBase):
        """Specific class for a dm-multipath based LUN"""

        def __init__(self):
            super(MpathCollection.MpathLUN, self).__init__()
            self.local_id_name = "Alias"

        def _read_partitions(self):
            # Partitions on dm-multipath devices appear as
            # /sys/class/block/dm-X/holders/dm-Y
            root_path = os.path.join(self.BLOCK_BASE, self.mapping, "holders")
            parts = {}
            for holder in os.listdir(root_path):
                # /sys/class/block/dm-X/holders/dm-Y/dm/name holds the name that
                # dm-multipath refers to the parition as (e.g. wwnpN or aliaspN)
                dm_name = os.path.join(root_path, holder, "dm", "name")
                # /sys/class/block/dm-X/holders/dm-Y/dev holds the major:minor value
                dev_path = os.path.join(root_path, holder, "dev")
                if os.path.exists(dm_name):
                    dev = None
                    with open(dm_name, "r") as f:
                        part = f.read().strip()
                    if os.path.exists(dev_path):
                        with open(dev_path, "r") as f:
                            dev = f.read().strip()
                    parts[os.path.join("/dev/mapper", part)] = dev
            return parts

        def rescan_paths(self):
            # dm-multipath needs to call `multipathd resize map` after
            # the underlying paths have been rescanned
            rc = super(MpathCollection.MpathLUN, self).rescan_paths()
            if rc != RExit.OK:
                return rc
            resize_cmd = "%s resize map %s" % (MpathCollection.MPIO_CMD, self.map_name)
            (rc, stdout, stderr) = Server.run_command(resize_cmd)
            if rc != 0:
                return command_fail(resize_cmd, stderr, stdout)
            sleep(SETTLE_TIME)
            return RExit.OK

        def _check_conf_file(self, conf, readconfdir=False):
            retval = False
            confdir = "/etc/multipath/conf.d"
            with open(conf, "r") as f:
                for line in f:
                    if line.strip().startswith("#"):
                        continue
                    vals = line.split()
                    if readconfdir and "config_dir" in vals:
                        confdir = vals[1].strip('"').strip()
                    elif "wwid" in vals:
                        if vals[1].lower() == "3%s" % self.wwn.lower():
                            retval = True
                            break
            return (retval, confdir)

        def list_config_files(self):
            """List any config files the LUN is present in"""
            conf_files = []
            conf = "/etc/multipath.conf"
            (used, confdir) = self._check_conf_file(conf, True)
            if used:
                conf_files.append(conf)
            for conf in [c for c in os.listdir(confdir) if c.endswith(".conf")]:
                conf = os.path.join(confdir, conf)
                (used, _) = self._check_conf_file(conf)
                if used:
                    conf_files.append(conf)
            return conf_files

        def remove(self):
            conf_files = self.list_config_files()
            if conf_files:
                logger.note(
                    "%s is still active in the following config files:\n\n  %s\n\n"
                    "Ensure the configurations are updated after LUN removal is complete."
                    % (self.wwn, "\n  ".join(conf_files))
                )
            cmd = "multipath -f %s" % self.map_name
            (rc, stdout, stderr) = Server.run_command(cmd)
            if rc != 0:
                return command_fail(cmd, stderr)
            sleep(SETTLE_TIME)
            return super(MpathCollection.MpathLUN, self).remove()

        @property
        def map_name(self):
            # Either the alias for the LUN, or the scsi ID
            # scsi ID is '3' + WWN
            if self.local_id and self.local_id != self.wwn:
                return self.local_id
            else:
                return "3%s" % self.wwn

        @property
        def mapping_path(self):
            # /dev/mapper/alias or /dev/mapper/'3'+wwn
            return os.path.join("/dev/mapper", self.map_name)

        @property
        def partprobe_cmd(self):
            return "kpartx -a %s" % self.mapping_path

        @property
        def extra_print_info(self):
            info = "DM Path: /dev/%s" % self.mapping
            super_info = super(MpathCollection.MpathLUN, self).extra_print_info
            if super_info:
                return "\n".join([info, super_info])
            return info

    def _add_entry(self, entry):
        super(MpathCollection, self)._add_entry(entry)
        # Also allow lookup by dm-X
        self.luns_by_dm[entry.mapping.lower()] = entry
        # Also allow lookup by alias if one exists
        if entry.local_id != entry.wwn:
            self.luns_by_alias[entry.local_id.lower()] = entry

    def _read_luns(self):
        cmd = "%s list maps json" % self.MPIO_CMD
        (rc, stdout, stderr) = Server.run_command(cmd)
        if rc != 0:
            logger.error("Error running %s: %s" % (cmd, stderr))
            return
        lundict = json.loads(stdout)
        for lun in list(lundict["maps"]):
            lunentry = MpathCollection.MpathLUN()
            lunentry.wwn = self.format_lunid(str(lun["uuid"]))
            if lun["uuid"] == lun["name"]:
                # No alias set, so use the formatted WWN we already have
                lunentry.local_id = lunentry.wwn
            else:
                # Alias for the LUN
                lunentry.local_id = str(lun["name"])
            # This is the dm-X entry
            lunentry.mapping = str(lun["sysfs"])
            for path in [p for pg in lun["path_groups"] for p in pg["paths"]]:
                lunentry.paths.append(str(path["dev"]))
            self._add_entry(lunentry)

    def format_lunid(self, lunid):
        dm_mtch = re.match(r"(?:/?dev/)?(dm-.*)", lunid)
        dev_mtch = re.match(r"(?:/?dev/mapper/)?(.*)", lunid)
        if dm_mtch:
            # Some form of dm-X from /dev
            lunid = dm_mtch.group(1)
        elif dev_mtch:
            # Some name from /dev/mapper (wwn or alias)
            lunid = dev_mtch.group(1)
        return super(MpathCollection, self).format_lunid(lunid)

    def get_lun(self, lunid):
        lunid = self.format_lunid(lunid).lower()
        lun = super(MpathCollection, self).get_lun(lunid)
        if not lun:
            lun = self.luns_by_dm.get(lunid, None)
        if not lun:
            lun = self.luns_by_alias.get(lunid, None)
        return lun

    def post_scan(self):
        sleep(SETTLE_TIME)
        self.read_luns()
        return RExit.OK

    def post_removal(self):
        cmd = "%s reconfigure" % self.MPIO_CMD
        (rc, stdout, stderr) = Server.run_command(cmd)
        if rc != 0:
            return command_fail(cmd, stderr)
        sleep(SETTLE_TIME)
        return RExit.OK


def check_for_sgutils():
    """Verify that the required binaries from sg3_utils are available"""

    for util in ["sg_turs", "sg_inq"]:
        if not cmd_exists("/usr/bin/%s" % util):
            logger.error("Didn't find command %s - ensure that sg3_utils is installed" % util)
            return False
    return True


def is_ghost_path(dev_path):
    """Determine if the path is a ghost lun"""

    # dev_path = /sys/class/scsi_device/h:b:t:l
    # Then /sys/class/scsi_device/h:b:t:l/device/generic is a symlink
    # to scsi_generic/sgN - so sg_dev = /dev/sgN
    sg_dev = "/dev/%s" % os.readlink(os.path.join(dev_path, "device", "generic")).split("/")[1]
    sg_turs_cmd = "/usr/bin/sg_turs %s" % sg_dev
    sg_inq_cmd = "/usr/bin/sg_inq --hex --vpd %s" % sg_dev

    # sg_turs result codes:
    # 0 = device ready
    # 99 = some unclassified error (implies ghost LUN)
    sg_turs = Server.run_command(sg_turs_cmd)

    # Sample sg_inq result:
    # VPD INQUIRY, page code=0x00:
    #  00     20 00 00 08 00 80 83 86  8f b0 b1 b2                ............
    # We are interested in the 2nd hex value (i.e. 20)
    sg_inq = Server.run_command(sg_inq_cmd)
    pq_str = sg_inq[1].splitlines()[1].split()[1]
    # From sg_inq.c source
    # pqual = (rp[0] & 0xe0) >> 5;
    # 0xe0 == 224
    # 0 = normal LUN
    # 1 = PQ indicates LU temporarily unavailable
    # 3 = PQ indicates LU not accessible via this port
    # else reserved or vendor specific qualifier
    pq_val = (int(pq_str, base=16) & 224) >> 5
    if sg_turs[0] == 99 and pq_val == 1:
        return True
    return False


def scan_unused_hlus(options, fcd=None):
    """Scan unused FC luns"""

    scsi_dev_base = "/sys/class/scsi_device/%s"
    skipped, scanned, ghosts = ([], [], [])
    if not check_for_sgutils():
        return RExit.ERR_CMD_FAIL
    if not fcd:
        fcd = FCData()
    for tgt in fcd.fc_targets:
        logger.info("Scanning LUNs on target %s:%s:%s" % tgt)
        scan_path = "/sys/class/scsi_host/host%s/scan" % tgt[0]
        # Scan all reasonable HLUs
        # Technically 0-16384 are valid,
        # however the lpfc module sets a default maximum of 256
        for hlu in list(range(256)):
            scsi_address = "%s:%s:%s:%s" % (tgt + (hlu,))
            # example dev_path: /sys/class/scsi_device/1:0:0:1
            dev_path = scsi_dev_base % scsi_address
            if os.path.exists(dev_path):
                logger.debug("Not scanning %s because it is already in use" % scsi_address)
                skipped.append(scsi_address)
                continue
            scan_address = "%s %s %s" % (tgt[1:3] + (hlu,))
            writefile(scan_path, scan_address)
            if os.path.exists(dev_path) and is_ghost_path(dev_path):
                del_address = os.path.join(dev_path, "device", "delete")
                writefile(del_address, "1")
                ghosts.append(scsi_address)
                if options.ghost_stop:
                    logger.info("Ghost LUN found on %s, moving to next target" % scsi_address)
                    break
            scanned.append(scsi_address)
    logger.debug("Scanned these addresses: \n\t%s" % ", ".join(scanned))
    logger.debug("Skipped these addresses: \n\t%s" % ", ".join(skipped))
    logger.debug("Removed these addresses as ghost LUNs: \n\t%s" % ", ".join(ghosts))
    return RExit.OK


def add_lun(options):
    """Scan for a new LUN"""
    lun = None
    luns = LUNCollection.factory()
    # Check if requested LUN is already present
    # Exit if it already is
    if options.lunid and luns.lun_exists(options.lunid):
        logger.note("%s is already configured. Exiting" % options.lunid)
        return RExit.OK

    pre_scan_lunids = luns.lunids

    # Scan for new LUN(s)
    rc = scan_all(options)
    if rc != RExit.OK:
        return rc

    # Perform post-scan action on LUN device
    luns.post_scan()
    post_scan_lunids = luns.lunids
    # We might have found more than one LUN, so list them all
    newluns = False
    for lunid in post_scan_lunids:
        if lunid not in pre_scan_lunids:
            newluns = True
            logger.note("Found new LUN %s mapped as %s" % (lunid, luns.get_lun(lunid).mapping_path))
    if options.lunid:
        lun = luns.get_lun(options.lunid)
        if not lun:
            logger.error(
                "Unable to find new LUN %s in configuration - check manually" % options.lunid
            )
            return RExit.ERR_LUN_MISSING
    if not newluns:
        logger.note("No new LUNs discovered by scan")
        return RExit.OK

    # Partition & pvcreate if needed
    if options.partition:
        if lun.has_data:
            logger.error(
                "LUN appears to have data already (the first 16MB is not zeroed"
                " out). Not writing a partition table - validate manually"
            )
            return RExit.ERR_LUN_INUSE
        rc = lun.partition_lun(options)
        if rc != RExit.OK:
            return rc
        if options.pvcreate:
            rc = lun.pvcreate()
            if rc != RExit.OK:
                return rc
        logger.note("Partitioning complete. New partition: %s" % lun.partitions[0])
    if not options.ignore_cluster and is_clustered():
        if options.partition:
            logger.note(
                "Clustered/shared LVM is in use. Run this tool on all other "
                "nodes in the cluster (without --writepartition) to scan in the"
                "new LUN BEFORE running any LVM commands"
            )
        else:
            logger.note(
                "Clustered/shared LVM is in use. Before using the LUN in LVM or"
                " any other service:\n - Manually create the partition and PV "
                "on this node\n - Run this tool on ALL the other nodes to scan "
                "for the new LUN\n - If the LUN is already present on the other"
                "nodes, run 'partprobe' on each of those nodes"
            )
    return RExit.OK


def remove_lun(options):
    """Remove an existing LUN"""

    luns = LUNCollection.factory()
    # Find existing LUN - exit if it can't be found
    lun = luns.get_lun(options.lunid)
    if not lun:
        logger.error("LUN %s not found on server" % options.lunid)
        return RExit.ERR_LUN_MISSING

    # Check if LUN is in use - exit if it is
    used = lun.used
    if used:
        logger.note(
            "LUN %s active in the following locations:\n  %s"
            % (lun.mapping_path, "\n  ".join(used))
        )
        logger.error("LUN is still in use. Exiting")
        return RExit.ERR_LUN_INUSE

    # Prompt for confirmation if necessary
    print("LUN to remove:")
    print_lun_info(lun)
    if not (
        options.force or confirm("Confirm you really want to remove LUN %s" % lun.mapping_path)
    ):
        return RExit.ERR_USR_CANCELLED

    # Run removal action on LUN - this also deletes the underlying paths
    rc = lun.remove()
    if rc != RExit.OK:
        logger.error("Error removing LUN %s. Please investigate manually" % lun.mapping_path)
        return rc
    logger.note("Successfully removed LUN: %s" % lun.mapping_path)
    logger.note("Contact the storage team to unpresent LUN %s from this host" % lun.wwn)

    # Perform post-removal action on LUN?
    rc = luns.post_removal()
    if rc != RExit.OK:
        return rc
    return RExit.OK


def rescan_lun(options):
    """Rescan the paths for an existing lun"""
    luns = LUNCollection.factory()
    # Find existing LUN - exit if it can't be found
    lun = luns.get_lun(options.lunid)
    if not lun:
        logger.error("LUN %s not found on server" % options.lunid)
        return RExit.ERR_LUN_MISSING

    # Prompt for confirmation if necessary
    print("LUN to rescan:")
    print_lun_info(lun)
    if lun.oracleasm_used():
        logger.warn(
            "This LUN appears to be used by Oracle. "
            "Rescanning may cause timeouts or crashes, proceed with caution"
        )
    if not (options.force or confirm("Rescan paths for %s" % lun.mapping_path)):
        return RExit.ERR_USR_CANCELLED

    old_size = lun.size
    # Loop through the paths and rescan them
    rc = lun.rescan_paths()
    if rc == RExit.OK:
        logger.note(
            "Rescanned paths for %s\n  Size before: %s\n  Size after: %s\n"
            % (lun.mapping_path, bytes_to_human(old_size), bytes_to_human(lun.size))
        )
    return rc


def lun_list(options):
    """Output information about all LUNs"""
    luns = LUNCollection.factory().luns
    if not luns:
        logger.note("No LUNs detected")
        return RExit.ERR_LUN_MISSING
    if not options.list_full and not options.list_noheadings:
        if options.list_detail:
            print(",".join(["WWN", "Mapping", "Size (GiB)", "Vendor"]))
        else:
            print(",".join(["WWN", "Mapping"]))
    for lun in luns:
        if options.list_full:
            print("=" * 37)
            print_lun_info(lun)
        elif options.list_detail:
            print(",".join([lun.wwn, lun.mapping_path, bytes_to_gib(lun.size), lun.vendor]))
        else:
            print(",".join([lun.wwn, lun.mapping_path]))
    return RExit.OK


def lun_info(options):
    """Output information about the selected LUN"""
    luns = LUNCollection.factory()
    lun = luns.get_lun(options.lunid)
    if not lun:
        logger.error("LUN %s not found on server" % options.lunid)
        return RExit.ERR_LUN_MISSING
    print_lun_info(lun)


def print_lun_info(lun):
    print("WWN: %s" % lun.wwn)
    extra_info = lun.extra_print_info
    if extra_info:
        print(extra_info)
    print("Mapping: %s" % lun.mapping_path)
    print("Vendor: %s" % lun.vendor)
    print("Block Devices: %s" % lun.paths)
    print("Usage:\n  %s" % "\n  ".join(lun.used or ["None"]))
    print("LUN Size: %s" % bytes_to_human(lun.size))


def scan_all(options):
    """Scan unused hosts & paths/HLUs"""

    fcd = FCData()
    scan_path = "/sys/class/scsi_host/host%s/scan"
    # Perform unused HLU scan on all fc_hosts with fc_transport info
    # Skip this if we are rescanning the entire buses
    if not options.scanall:
        rc = scan_unused_hlus(options, fcd)
        if rc != RExit.OK:
            return rc

    # Perform full scan ("- - -") on any fc hosts without fc_transport info
    # Or rescan everything if asked to
    no_scan = fcd.transport_hosts
    if options.scanall:
        if oracle_in_use():
            logger.warn(
                "Oracle DB appears to be in use on this server, and you have asked "
                "to perform a full rescan\nThis may cause a reset of the SCSI bus "
                "and interrupt I/O to Oracle, which can cause Oracle to crash\n"
                "Proceed with extreme caution"
            )
        if not (options.force or confirm("Perform full SCSI rescan (may interrupt I/O)")):
            return RExit.ERR_USR_CANCELLED
        no_scan = []
    for host in [h for h in fcd.active_hosts if h not in no_scan]:
        writefile(scan_path % host, "- - -")
    return RExit.OK


def sigbye_handler(signum, frame):
    """Exit function triggered by caught signals"""
    print("\nSignal handler called with signal: {}".format(signum))
    print(frame)
    sys.exit(RExit.ERR_USR_CANCELLED)


def parse_args():
    """Accept input from user to control what is done"""
    parser = optparse.OptionParser(
        version="%prog v{0}".format(__version__), formatter=IndentedListFormatter()
    )

    parser.add_option(
        "-n", "--dry-run", help=SUPPRESS_HELP, action="store_true", dest="dry_run", default=False
    )

    parser.add_option(
        "-a",
        "--action",
        type="choice",
        choices=["add", "remove", "rescan", "info", "list"],
        help="Task to be done at LUN Level (add, remove, rescan, info, list)",
        dest="action",
    )
    parser.add_option(
        "-i",
        "--lunid",
        action="store",
        help=(
            "LUN Identifier (LUNID/WWN) or Device Mapping(emcpowerX)",
            "Required: (remove, rescan, info)",
            "Optional: (add)",
        ),
        dest="lunid",
    )
    parser.add_option(
        "-f",
        "--force",
        help="Skip confirmations (use with caution)",
        action="store_true",
        default=False,
        dest="force",
    )
    parser.add_option(
        "-v",
        "--verbose",
        help="Verbose level logging",
        action="store_true",
        default=False,
        dest="verbose",
    )
    parser.add_option(
        "-d",
        "--debug",
        help="Debug level logging",
        action="store_true",
        default=False,
        dest="debug",
    )
    group = OptionGroup(parser, "Specific Options for (-a add)")
    group.add_option(
        "--writepartition",
        default=False,
        action="store_true",
        help=("Write a single, GPT, aligned, full disk partition", "(-i required)"),
        dest="partition",
    )
    group.add_option(
        "--pvcreate",
        default=False,
        action="store_true",
        help=(
            "Create a PV on the partition",
            "(only applicable with --writepartition, -i required)",
        ),
        dest="pvcreate",
    )
    group.add_option(
        "--nowritelvmlabel",
        default=False,
        action="store_true",
        help=(
            "Don't tag partition for LVM",
            "(only applicable with --writepartition, -i required)",
        ),
        dest="nolvmtag",
    )
    group.add_option(
        "--noclvmcheck",
        default=False,
        action="store_true",
        help="Don't check for CLVM/lvmlockd, consider server as standalone",
        dest="ignore_cluster",
    )
    group.add_option(
        "--scanall",
        default=False,
        action="store_true",
        help="Rescan entire SCSI bus - caution, may interrupt I/O",
        dest="scanall",
    )
    group.add_option(
        "--noghoststop",
        default=True,
        action="store_false",
        help=("Don't stop scanning a target when a ghost LUN is found", "(default is to stop)"),
        dest="ghost_stop",
    )
    parser.add_option_group(group)

    group = OptionGroup(parser, "Specific Options for (-a list)")
    group.add_option(
        "--details",
        default=False,
        action="store_true",
        help="Output a detailed list of LUN information, one line per LUN",
        dest="list_detail",
    )
    group.add_option(
        "--fullinfo",
        default=False,
        action="store_true",
        help="Output the same information as -a info for each LUN",
        dest="list_full",
    )
    group.add_option(
        "--noheadings",
        default=False,
        action="store_true",
        help="Don't print headings (doesn't apply to --fullinfo)",
        dest="list_noheadings",
    )
    parser.add_option_group(group)

    return parser


def validate_args(parser, options, args):
    valid = True

    # Lists of options that are only valid for specific actions
    action_opts = {
        "add": [
            "--scanall",
            "--writepartition",
            "--pvcreate",
            "--nowritelvmlabel",
            "--noclvmcheck",
            "--noghoststop",
        ],
        "list": ["--details", "--fullinfo", "--noheadings"],
        "remove": [],
        "info": [],
        "rescan": [],
    }
    lunid_required_actions = ["remove", "info", "rescan"]
    lunid_optional_actions = ["add"]
    # Options that are incompatible with each other
    incompatible_options = [
        ("--pvcreate", "--nowritelvmlabel"),
        ("--fullinfo", "--noheadings"),
        ("--fullinfo", "--details"),
    ]
    # Options where if the first one listed is present, so must the second one
    paired_options = [
        ("--pvcreate", "--writepartition"),
        ("--nowritelvmlabel", "--writepartition"),
        ("--writepartition", "--lunid"),
        ("--pvcreate", "--lunid"),
        ("--nowritelvmlabel", "--lunid"),
    ]

    if not options.action:
        valid = False
        logger.error("An action is required. Please use the '-a/--action' flag")
        parser.print_help()
    if options.action in lunid_required_actions and not options.lunid:
        valid = False
        logger.error("A LUN ID is required for the %s action" % options.action)
    if options.action not in lunid_required_actions + lunid_optional_actions and options.lunid:
        valid = False
        logger.error("A LUN ID should not be supplied for the %s action" % options.action)
    # Check that options that are valid only for specific actions don't appear
    # unless the specifc action is being used
    for action, exc_opts in [(k, v) for k, v in action_opts.items() if v]:
        if options.action != action:
            for opt in [parser.get_option(o) for o in exc_opts if parser.has_option(o)]:
                if opt.dest and getattr(options, opt.dest) != opt.default:
                    valid = False
                    logger.error("The %s option is only valid for the %s action" % (opt, action))
    # Check options that require another option to be set too
    for opt1, opt2, opt_pair in [
        (parser.get_option(o1), parser.get_option(o2), (o1, o2)) for o1, o2 in paired_options
    ]:
        if (
            opt1.dest
            and getattr(options, opt1.dest) != opt1.default
            and opt2.dest
            and (getattr(options, opt2.dest) == opt2.default or getattr(options, opt2.dest) is None)
        ):
            valid = False
            logger.error("'%s' requires '%s'" % opt_pair)
    # Check options that are incompatible with each other
    for opt1, opt2, opt_pair in [
        (parser.get_option(o1), parser.get_option(o2), (o1, o2)) for o1, o2 in incompatible_options
    ]:
        if (
            opt1.dest
            and getattr(options, opt1.dest) != opt1.default
            and opt2.dest
            and getattr(options, opt2.dest) != opt2.default
        ):
            valid = False
            logger.error("'%s' and '%s' cannot be used together" % opt_pair)
    return valid


def main():
    parser = parse_args()
    config.options, args = parser.parse_args()
    log_level = get_log_level()
    customize_logger(log_level)
    if not validate_args(parser, config.options, args):
        logger.error("Invalid command usage.")
        return RExit.ERR_USAGE

    if config.options.action in "add":
        return add_lun(config.options)
    if config.options.action in "remove":
        return remove_lun(config.options)
    if config.options.action in "rescan":
        return rescan_lun(config.options)
    if config.options.action in "info":
        return lun_info(config.options)
    if config.options.action in "list":
        return lun_list(config.options)

    # should never be reached
    return RExit.ERR_GENERAL


if __name__ == "__main__":
    # register the signal handlers/callback
    signal.signal(signal.SIGINT, sigbye_handler)
    signal.signal(signal.SIGQUIT, sigbye_handler)
    signal.signal(signal.SIGTERM, sigbye_handler)

    # https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_08_02
    # 2.8.2 Exit Status for Commands
    #  If a command is not found, the exit status shall be 127.
    #  If the command name is found, but it is not an executable utility,
    #  the exit status shall be 126.
    try:
        sys.exit(main())
    except CommandPermissionError as e:
        logger.critical(e)
        sys.exit(RExit.ERR_CMD_NOT_EXECUTABLE)
    except CommandNotFoundError as e:
        logger.critical(e)
        sys.exit(RExit.ERR_CMD_NOT_FOUND)
