#!/usr/bin/python

import optparse
import os
import re
import signal
import sys
from optparse import SUPPRESS_HELP
from platform import linux_distribution

from rs_block_storage.helpers.config import config
from rs_block_storage.helpers.log import customize_logger, logger
from rs_block_storage.rbs import get_log_level
from rs_block_storage.server.server import Server
from rs_block_storage.version import __version__


class LUNCore(object):
    """Core logic applicable to multiple types of backing storage"""

    def __init__(self):
        distro, version, _ = linux_distribution(full_distribution_name=False)

    def dict_generator(self, lun, action, skip, partition, lvmtag, clustered, force):
        """Generates a dictionary with information needed by other methods"""
        lundata = {}

        lun = self.format_lunid(lun)
        if not lun:
            raise ValueError("ID formatting error")

        vendor = self.determine_vendor(action, lun)
        if not vendor:
            raise ValueError("could not find vendor")

        # Perform LUNID validity tests, unless "-s" passed at CLI
        if skip:
            logger.debug("Skipping LUNID validity tests.")
        else:
            valid = self.validate_lun_input(action, lun, vendor)
            if not valid[0]:
                raise ValueError(valid[1])

        lundata["lun"] = lun
        lundata["vendor"] = vendor
        lundata["oracle"] = self.oracle_check()
        lundata["partition"] = partition
        lundata["lvmtag"] = lvmtag
        lundata["action"] = action
        lundata["force"] = force

        if clustered:
            lundata["clustered"] = False
        else:
            lundata["clustered"] = self.clustered_check()

        return lundata

    def format_lunid(self, lunid):

        # The linux kernel may sometimes add an additional 3 to an ID.
        # We remove this to ensure we have the actual valid ID
        if len(lunid) > 20:
            if lunid.startswith("3"):
                lunid = lunid[1:]

        lunid = self.determine_mapping(lunid)
        lunid = re.sub("[^A-Za-z0-9]+", "", lunid)

        return lunid

    def determine_vendor(self, action, formattedlunid):
        retkey = None
        vendordict = {"emc": ["000097", "006016"], "pure": ["24A937"]}

        # EMC's PowerPath might be using "Logical IDs", which are vendor-specific,
        #   proprietary, and shorter than 32-characters.  Everything else should
        #   be 32-chars.  As such, <32 means EMC.

        if len(formattedlunid) < 32:
            if action in "remove":
                logger.debug(formattedlunid)
                if formattedlunid.startswith("emc"):
                    return "emc"
                else:
                    raise ValueError("Using LUN Mapping for non-EMC LUNs not implemented")
            else:
                logger.debug("LUNID length < 32 chars.  Assuming vendor=EMC.")
                return "emc"

        tempid = formattedlunid[1:].lower()
        for key, values in vendordict.items():
            if retkey:
                break
            logger.info("Validating WWN against vendor codes for vendor: %s" % key.upper())
            for value in values:
                logger.debug("Value: %s - ID: %s" % (value.lower(), tempid[:6]))
                if tempid.startswith(value.lower()):
                    logger.debug("ID matched to vendor: %s" % key)
                    retkey = key
                    break

        logger.info("Vendor Found: %s" % retkey)
        return retkey

    def determine_mapping(self, mapping):
        if mapping.startswith("/") and not mapping.endswith("/"):
            splitmap = mapping.split("/")
            return splitmap[-1]
        elif mapping.endswith("/"):
            raise ValueError("Invalid LUN ID")
        else:
            return mapping

    def clustered_check(self):
        clustered = False

        try:
            cmd = Server.run_command("pgrep clvmd")
        except Exception:
            logger.error("There was a problem running pgrep")
            clustered = "NA"
            return clustered

        clustered = bool(cmd[1])

        return clustered

    def validate_lun_input(self, action, lunid, storage_vendor, hlu=None):
        valid = [False, None]  # [validity, ErrorMessage]

        # First test syntactic charset validity - should be hex
        if action not in "remove":
            idvalidation = re.search("^[A-Fa-f0-9]*$", lunid)
            if not idvalidation:
                valid = [
                    False,
                    (
                        "LUNID/WWN %s is invalid. Must contain only "
                        "numerical characters and/or letters A-F" % lunid
                    ),
                ]
                return valid

        # Now test for expected values (ie: length)
        valid = getattr(vendor(storage_vendor), ("%s_lun_input_validation" % storage_vendor))(lunid)

        return valid

    def oracle_check(self):
        processes = Server.run_command("ps -ef")
        search = ["ora", "oracle", "asm_"]
        result = False

        logger.info("Checking if Oracle is on this server")
        for process in processes[1].splitlines():
            if any(x in process for x in search):
                result = True
        logger.debug("Oracle Processes: %s" % result)
        if not result:
            if os.path.exists("/etc/oratab"):
                result = True
            logger.debug("/etc/oratab exists: %s" % result)

        return result


class EMC(LUNCore):
    def __init__(self, lundata):
        LUNCore.__init__(self)
        self.lundata = lundata
        self.path = self.emc_get_path()

    def emc_lun_input_validation(self, lunid):
        result = [False, None]

        try:
            Server.run_command("powermt version")
        except Exception:
            result = [
                False,
                (
                    "LUNID Provided is for EMC, but Powerpath not "
                    "found on server. Please verify this server is "
                    "configured for EMC based LUNs "
                ),
            ]
            return result

        logger.info("Validating if using device mapping for LUNID")
        if lunid.startswith("emcpower"):
            return [True, None]

        logger.info("Validating LUNID based on length")

        # Universal standard is WWN, which is 32 hex chars
        if len(lunid) == 32:
            logger.debug("LUNID length is 32, which is valid for VNX.")
            return [True, None]

        # VMAX violates that standard and uses shorter logical IDs.
        #   Historically, we've seen these be 4, 5, and 8 chars in length.
        vmaxlength = (4, 5, 8)
        logger.debug("Checking for vmax lengths: %s" % str(vmaxlength))
        if len(lunid) in vmaxlength:
            logger.debug("LUNID length is %s" % len(lunid))
            return [True, None]

        # If we get a non-32, non-[4|5|8] length, it was probably a typo.
        logger.debug("LUNID could not be validated vs known formats")
        result = [
            False,
            (
                "LUNID/WWN %s has unexpected length. Should be "
                "4/5/8 (VMAX) or 32 (VNX) characters long, but "
                "is %d characters long" % (lunid, len(lunid))
            ),
        ]
        return result

    def emc_get_current_luns(self):
        powermt = "powermt display dev=all"
        currentluns = None

        # We use EMC's proprietary tool to get the information that it sees
        try:
            currentluns = Server.run_command(powermt)[1]
        except Exception:
            logger.error("Unable to use powermt")

        return currentluns.splitlines()

    def emc_lun_exist(self, lunid):
        current_luns = self.emc_get_current_luns()
        searchstring = [
            ("Logical device ID=%s" % lunid),
            ("Device WWN=%s" % lunid),
            ("Pseudo name=%s" % lunid),
        ]

        # We loop through the powermt output matching for both logical IDs
        # and WWNs to cover both shared and dedicated SAN
        for entry in current_luns:
            if any(item in entry for item in searchstring):
                formatted_entry = entry.split("=")[1].split(" ")[0]
                if lunid == formatted_entry:
                    return True

        return False

    def emc_get_pseudo_info(self, pseudoname):
        pmt_data = Server.run_command("powermt display dev=%s" % pseudoname)[1]
        return pmt_data

    def list_pseudonames(self):
        pseudonames = list()
        searchstring = "Pseudo name="
        pmt_data = self.emc_get_current_luns()

        # Loop through the data, find the pseudo name line, and we split at
        # the '=' and get the entry after it
        for line in pmt_data:
            if searchstring in line:
                pseudonames.append(line.split("=", 1)[1])
        return pseudonames

    def emc_get_mapping(self, lunid):
        searchstring = "Logical device ID=%s" % lunid
        searchstring2 = "Device WWN=%s" % lunid
        ret_pseudo = None

        # Take out lunid input, find it in our pseudo name list and return it
        for pseudo in self.list_pseudonames():
            pseudo_info = self.emc_get_pseudo_info(pseudo)
            if searchstring in pseudo_info or searchstring2 in pseudo_info:
                ret_pseudo = pseudo
        return ret_pseudo

    def configure_powermt(self):
        config = "powermt config"
        save = "powermt save"
        config_result = False
        save_result = False

        try:
            config_result = Server.run_command(config)[0]
        except Exception as e:
            logger.error("There was an error configuring powermt: %s" % e)

        try:
            save_result = Server.run_command(save)[0]
        except Exception as e:
            logger.error("There was an error saving powermt configuration: %s" % e)

        if save_result != 0 or config_result != 0:
            return False

        return True

    def emc_add_lun(self, lundata):

        result = self.configure_powermt()
        if not result:
            logger.error(
                "There was a problem with configuring powermt and saving. "
                "Please manually validate"
            )
            return
        exists = self.emc_lun_exist(lundata["lun"])
        if not exists:
            logger.error(
                "Was not able to find new LUN in powermt configuration. Please check manually"
            )
            return

        logger.info("LUN %s successfully added" % lundata["lun"])

        pseudo = self.emc_get_mapping(lundata["lun"])
        logger.note("Successfully added LUN %s in as /dev/%s" % (lundata["lun"], pseudo))

    def emc_is_in_use(self, lundata):
        self.path = self.emc_get_path()
        if "remove" in lundata["action"] and lundata["lun"].startswith("emc"):
            pseudo = lundata["lun"]
        else:
            pseudo = self.emc_get_mapping(lundata["lun"])
        disklogic = Disk_Logic(self.path, pseudo, lundata)
        in_use = disklogic.in_use_checks()

        return in_use

    def emc_remove_lun(self, lundata):
        release = "powermt release"
        save = "powermt save"
        release_result = False
        save_result = False

        if "remove" in lundata["action"] and lundata["lun"].startswith("emc"):
            pseudo = lundata["lun"]
        else:
            pseudo = self.emc_get_mapping(lundata["lun"])
        disks = self.emc_get_disks(pseudo)
        result = [True, disks]

        try:
            command = Server.run_command("powermt remove dev=%s" % pseudo)
        except Exception:
            logger.error(
                "Failure trying to remove lun from Powerpath "
                "configuration. Please verify manually and try "
                "again"
            )
            result[0] = False

        if command[0] != 0:
            result[0] = False
        else:
            try:
                release_result = Server.run_command(release)[0]
            except Exception as e:
                logger.error("There was an error releasing powermt: %s" % e)

            try:
                save_result = Server.run_command(save)[0]
            except Exception as e:
                logger.error("There was an error saving powermt configuration: %s" % e)

            if save_result != 0 or release_result != 0:
                result[0] = False

        return result

    def emc_get_disks(self, pseudo):
        pseudo_info = self.emc_get_pseudo_info(pseudo)
        disk_list = []

        for line in pseudo_info.splitlines():
            if line.startswith(" "):
                path_info = [field for field in line.split(" ") if field]
                disk_list.append(path_info[2])

        return disk_list

    def emc_post_removal(self):
        logger.debug("No post removal steps for EMC at this time")
        return True

    def emc_partition(self, lundata):
        self.path = self.emc_get_path()
        pseudo = self.emc_get_mapping(lundata["lun"])
        disklogic = Disk_Logic(self.path, pseudo, lundata)

        disklogic.partition_lun(pseudo)

    def emc_get_path(self):
        return "/dev/"


class PURE(LUNCore):
    def __init__(self, lundata):
        LUNCore.__init__(self)
        self.lundata = lundata
        self.path = self.pure_get_path()

    def pure_get_current_luns(self):

        command = "multipathd show multipaths"

        try:
            currentluns = Server.run_command(command)[1]
        except Exception:
            logger.error("Unable to use multipath")

        return currentluns.splitlines()

    def pure_lun_exist(self, lunid):
        current_luns = self.pure_get_current_luns()

        # entry lines will show this format "name   sysfs uuid"
        # uuid is the WWN in the output, so we simply match for our input
        for entry in current_luns:
            if lunid in entry:
                logger.debug("%s found already configured" % lunid)
                return True

        return False

    def pure_lun_input_validation(self, lunid):

        result = [False, None]

        # Checking that multipath is configured to verify this is a server
        # that should be using PURE LUNs
        command = "multipathd list paths"
        try:
            multipath_in_use = Server.run_command(command)[0]
        except Exception:
            logger.error("Multipath was not useable on server")
        if multipath_in_use != 0:
            result = [
                False,
                (
                    "PURE WWN in use and Multipath found but not "
                    "configured. Ensure that this is a PURE "
                    "configured server"
                ),
            ]
        else:
            logger.info("Validating LUNID based on length")
            # PURE *always* uses WWN.  There's effectively no "lun id".
            # As such, *all* IDs referenced by PURE should be 32-chars
            if len(lunid) == 32:
                logger.debug("LUNID is of standard length")
                return [True, None]

            result = [
                False,
                "LUNID was not of appropriate length (found %d, "
                "expected 32). Please verify your input." % (len(lunid)),
            ]

        return result

    def pure_add_lun(self, lundata):
        lunid = lundata["lun"]
        found = 0

        # We need to check multipath for this LUN's existance, if it doesn't
        # we look at /dev/mapper directly
        if not self.pure_lun_exist(lunid):
            logger.debug("Was not able to find %s in multipath output" % lunid)
            try:
                command = "ls -latr /dev/mapper/"
                dev_mapper_output = Server.run_command(command)[1].splitlines()
            except Exception:
                logger.error(
                    "Error when looking at /dev/mapper. Please check the operating system."
                )
                return
            for line in dev_mapper_output:
                if lunid in line:
                    logger.note("Found %s in /dev/mapper" % lunid)
                    found += 1
        else:
            found = 1

        if found == 0:
            logger.error(
                "%s was not found on the server. Please manually "
                "validate that it has been added" % lunid
            )
            return

        print("LUNID: %s has been added to the server" % lunid)
        print(
            "Due to the nature of multipath and LUN naming, "
            "manual intervention is needed at this time"
        )
        print(
            "Use the following template to add the new LUN "
            "within the 'multipaths{}' section of the multipath "
            "configuration file(/etc/multipath.d for EL6 and "
            "/etc/multipath/conf.d/rackspace-luns.conf for EL7+)"
        )
        logger.note(
            "The Linux Kernel writes a 3 before the WWN which "
            "makes it a requirement for the address when adding "
            "to multipath."
        )
        print("\n  multipath {")
        print("    wwid    %s" % ("3" + lunid))
        print("    alias   pure01")
        print("  }")
        print("\n")
        logger.note(
            "The alias may be changed to follow the "
            "customer's naming conventions. Rackspace Best "
            "Practice is to name each LUN 'pure###'"
        )

    def pure_is_in_use(self, lundata):
        self.path = self.pure_get_path()
        mapping = self.pure_get_mapping(lundata["lun"])
        disklogic = Disk_Logic(self.path, mapping, lundata)
        in_use = disklogic.in_use_checks()

        return in_use

    def pure_get_mapping(self, lunid):
        command = "multipathd show multipaths"
        output = Server.run_command(command)[1].splitlines()
        name = None

        for line in output:
            if lunid in line:
                name = line.split(" ")[0]

        return name

    def pure_get_disks(self, mapping):
        command = "multipathd show map %s topology" % mapping
        output = Server.run_command(command)[1].splitlines()
        disks = []

        for line in output:
            if line.startswith(" "):
                disks.append(re.sub(r"[^a-zA-Z]+", " ", line).split()[0])

        return disks

    def pure_is_in_conf(self, lunid):
        mainconf = "/etc/multipath.conf"
        secondaryconfs = "/etc/multipath/conf.d/"
        active = False
        locations = []

        found = Server.run_command('grep -irl "%s" %s %s' % (lunid, mainconf, secondaryconfs))
        if found[0] == 0:
            for result in found[1].splitlines():
                locations.append(result)
            for location in locations:
                with open(location, "r") as f:
                    for line in f:
                        if lunid in line:
                            if not line.startswith("#"):
                                active = True

        return active

    def pure_remove_lun(self, lundata):
        lunid = "3" + lundata["lun"]
        mapping = self.pure_get_mapping(lunid)
        disks = self.pure_get_disks(mapping)
        result = [True, disks]

        if self.pure_is_in_conf(lunid):
            logger.error(
                "%s is still active in the multipath configurations. Manual intervention "
                "needed." % lunid
            )
            result[0] = False
        else:
            Server.run_command("multipath -f %s" % lunid)

        return result

    def pure_post_removal(self):
        response = False

        logger.debug("Reconfiguring multipathd")
        command = Server.run_command("multipathd reconfigure")

        # Reconfiguring multipathd to remove traces of lun we have removed
        if command:
            response = True

        return response

    def pure_partition(self, lundata):
        self.path = self.pure_get_path()
        mapping = self.pure_get_mapping(lundata["lun"])
        disklogic = Disk_Logic(self.path, mapping, lundata)

        disklogic.partition_lun(mapping)

    def pure_get_path(self):
        return "/dev/mapper/"


class SCSIBus(LUNCore):
    def __init__(self, lundata):
        LUNCore.__init__(self)
        self.lundata = lundata
        self.scsiinfo = self.get_scsi_info()

    def get_scsi_info(self):
        # We need to parse /proc/scsi/scsi to pull information and validate it
        # This file should look similar to this
        #
        # Attached devices:
        # Host: scsi0 Channel: 00 Id: 32 Lun: 00
        #   Vendor: DP       Model: BACKPLANE        Rev: 1.07
        #   Type:   Enclosure                        ANSI  SCSI revision: 05
        # Host: scsi0 Channel: 02 Id: 00 Lun: 00
        #   Vendor: DELL     Model: PERC 6/i         Rev: 1.22
        #   Type:   Direct-Access                    ANSI  SCSI revision: 05
        # Host: scsi1 Channel: 00 Id: 00 Lun: 01
        #   Vendor: EMC      Model: SYMMETRIX        Rev: 5874
        #   Type:   Direct-Access                    ANSI  SCSI revision: 05
        # Host: scsi3 Channel: 00 Id: 00 Lun: 01
        #   Vendor: EMC      Model: SYMMETRIX        Rev: 5874
        #   Type:   Direct-Access                    ANSI  SCSI revision: 05

        cmd = "cat /proc/scsi/scsi"
        scsihost = Server.run_command(cmd)[1].splitlines()
        templist = []
        hostdicts = []  # List of SCSI-Host dictionaries
        vendordict = {}  # Dictionary of Host-to-VendorSet

        if "Host: scsi" not in str(scsihost):
            logger.error("There was an error parsing /proc/scsi/scsi. Please investigate")
            raise OSError

        for line in scsihost:
            if line.startswith("Host"):
                line = re.sub("[:]", "", line)
                sline = line.split()
                templist.append(sline)
        for entry in templist:
            if len(entry) >= 8:
                hostdicts.append(
                    {entry[0]: entry[1], entry[2]: entry[3], entry[4]: entry[5], entry[6]: entry[7]}
                )
        current_host = None
        for line in scsihost:
            if "Host: scsi" in line:
                # Keep track of which scsiXX host we're currently reading
                current_host = line.split()[1]
            if "Vendor:" in line:
                # Found the vendor info for current_host - record it
                vendor = line.split()[1]
                vendordict[current_host] = vendor

        return hostdicts, vendordict

    def is_present(self, newaddr):
        existing_luns = []
        for hostline in self.scsiinfo[0]:
            # Generate a list of LUNs already present:
            # Note: 0-padded numbers are important here, because "scsi2 0 1 2"
            #   is _not in_ [ "scsi2 00 01 02" ]
            existing_luns.append(
                "%s %02d %02d %02d"
                % (
                    hostline["Host"],
                    int(hostline["Channel"]),
                    int(hostline["Id"]),
                    int(hostline["Lun"]),
                )
            )
        # Force newaddr into the same format, so 'in' comparison is valid:
        newaddr_lst = newaddr.split()
        newaddr_formatted = "%s %02d %02d %02d" % (
            newaddr_lst[0],
            int(newaddr_lst[1]),
            int(newaddr_lst[2]),
            int(newaddr_lst[3]),
        )
        return newaddr_formatted in existing_luns

    def scsi_rescan(self):
        idrange = list(range(9))
        channels = list(range(1))
        hbas = self.get_hbas()
        scanned = []
        skipped = []

        if not hbas or config.options.scanall:
            logger.debug("Rescanning all HBAs")
            SCSIBus.scanall()
            return

        for hba in hbas:
            logger.info("Scanning HBA %s" % hba)
            for channel in channels:
                for ids in idrange:
                    # Scan all reasonable HLUs:
                    # Note: Technically, 0-16384 are valid, but in practice
                    #   we've only seen as high as 125.
                    luns = list(range(256))
                    for lun in luns:
                        newaddr = "scsi%s %s %s %s" % (hba, channel, ids, lun)
                        if self.is_present(newaddr):
                            skipped.append(newaddr)
                            logger.debug(
                                "Not scanning %s address "
                                "%s:%s:%s because it's already "
                                "in use" % (hba, channel, ids, lun)
                            )
                        else:
                            scanned.append(newaddr)
                            address = "%s %s %s" % (channel, ids, lun)
                            self.hostfile_write(hba, address, "scan")

        logger.debug("Scanned for these addresses: \n%s" % (scanned))
        logger.debug("Skipped these addresses: \n%s" % (skipped))

    def scsi_remove(self, disks):
        result = True

        logger.debug("Removing these block devices from server %s" % disks)
        for disk in disks:
            path = "/sys/block/%s/device/delete" % disk
            with open(path, "w") as f:
                f.write("1")
            test = Server.run_command("ls %s" % path)
            if test[0] == 0:
                result = False

        return result

    def get_hbas(self):
        hbalist = []
        cmd = "ls -1 /sys/class/fc_transport"
        output = None

        try:
            output = Server.run_command(cmd)[1].splitlines()
        except Exception:
            logger.error("ls command not functioning")

        for line in output:
            # Remove everything after : in output line. Example: target2:0:0
            result = line.split(":")[0]
            # Take result and strip all non decimal characters
            sresult = re.sub(r"\D", "", result)
            hbalist.append(sresult)

        return hbalist

    @staticmethod
    def scanall():
        baselocation = "/sys/class/scsi_host/"
        hosts = Server.run_command("ls %s" % baselocation)[1]
        hosts = hosts.splitlines()

        for host in hosts:
            if len(host) > 6:
                logger.error("Unexpected entry in /sys/class/scsi_host/")
                raise OSError

        for host in hosts:
            scanfile = "%s%s/scan" % (baselocation, host)
            logger.debug("Writing '- - -' to %s" % scanfile)
            with open(scanfile, "w") as f:
                f.write("- - -")

    def hostfile_write(self, hba, address, action):
        baselocation = "/sys/class/scsi_host/host%s" % hba
        location = "%s/scan" % baselocation

        if action in "scan":
            with open(location, "w") as f:
                f.write(address)


class Disk_Logic(LUNCore):
    def __init__(self, path, mapping, lundata):
        LUNCore.__init__(self)
        self.path = path
        self.mapping = mapping
        self.osdisk = os.path.join(self.path, self.mapping)
        self.partitions = self.get_partitions(self.osdisk)
        self.lundata = lundata

    def get_partitions(self, osdisk):
        command = "lsblk %s" % osdisk
        partitions = []

        output = Server.run_command(command)[1].splitlines()
        # using lsblk to get list of partitions of the specified disk. Get the
        # first field and remove non-alphanumeric characters
        for line in output:
            # multipath based solutions will add an additional field such as (dm-2) this removes
            # this to keep it inline across vendors
            line = re.sub(r"[\(].*?[\)]", "", line)
            if "part" in line.split()[5]:
                entry = re.sub("[^A-Za-z0-9]+", "", line.split()[0])
                partitions.append(entry)

        return partitions

    def do_partitions_exist(self):
        result = False

        if self.partitions:
            result = True

        return result

    def pv_check(self, path):
        pv_used = [False, None]

        for partition in self.partitions:
            pvoutput = Server.run_command("pvdisplay %s%s" % (path, partition))
            if pvoutput[0] == 0:
                pv_used = [True, ("%s%s" % (path, partition))]

        return pv_used

    def standalone_mounted(self):
        mounted = False
        logger.debug("testing if mounted")
        with open("/proc/self/mounts", "r") as f:
            for line in f:
                for partition in self.partitions:
                    if partition in line:
                        mounted = True
        return mounted

    def fuser_check(self, path):
        in_use = False

        for partition in self.partitions:
            fuser = Server.run_command("fuser -m %s%s" % (path, partition))
            if fuser[0] == 0:
                in_use = True
        return in_use

    def used_by_oracle(self):
        logger.note(
            "Oracle has been detected running on this server. Please run the following "
            "command to validate it is not in use\n\n"
            '"lsof |grep  `grep -A1  %s /etc/udev/rules.d/99-oracle-grid.rules | '
            "awk -F\" '/NAME/ {print $(NF-1)}'|sed 's/%%n//' `\n" % self.mapping
        )

        return input_prompt("Have you run the check and confirmed it is not in use?")

    def in_use_checks(self):
        in_use = False

        if self.pv_check(self.path)[0]:
            in_use = True
            logger.debug("still configured as a physical volume")
        if self.standalone_mounted():
            in_use = True
            logger.debug("mounted on system")
        if self.fuser_check(self.path):
            in_use = True
            logger.debug("Found process utilizing disk")
        if self.lundata["oracle"]:
            oracle_check = self.used_by_oracle()
            if not oracle_check:
                in_use = True

        return in_use

    def partition_lun(self, mapping):
        table_creation = "parted -s %s mklabel gpt" % self.osdisk
        part_command = "parted -s %s mkpart %s 0%% 100%%" % (self.osdisk, mapping)
        lvmtag_command = "parted -s %s set 1 lvm on" % self.osdisk

        if self.do_partitions_exist():
            logger.note("Partition already exists. Partitioning task exiting")
            return

        try:
            Server.run_command(table_creation)
            partition_task = Server.run_command(part_command)
            if not self.lundata["lvmtag"]:
                Server.run_command(lvmtag_command)
        except Exception:
            logger.error("Error running parted command. Exiting")
            return
        if partition_task[0] != 0:
            logger.note("Error partitioning %s. Please manually validate." % (self.osdisk))
            return

        try:
            Server.run_command("partx -a %s" % self.osdisk)
        except Exception:
            logger.debug("Could not run partx command")

        partition_result = self.get_partitions(self.osdisk)
        if partition_result:
            logger.note("Partitioning Complete. New partition: %s" % partition_result)
        else:
            logger.error(
                "Partitioning is complete, but the new partition is not showing. Please validate "
                "the server"
            )

    def lunsize(self):
        parted_info = Server.run_command("parted -s %s print unit s" % self.osdisk)
        splitline = []

        if parted_info[0] == 1:
            return parted_info[1]

        for line in parted_info[1].splitlines():
            if "Disk /" in line:
                if len(line.split()) > 2:
                    splitline = line.split()[2]
                else:
                    splitline = "Parted output not valid. Check Disk"

        return splitline


class vendor(EMC, PURE):
    pass


def input_prompt(question):
    prompt = None
    answer = False

    real_raw_input = vars(__builtins__).get("raw_input", input)
    prompt = real_raw_input(question + " (y/n): ").lower().strip()

    if prompt == "y":
        answer = True
    elif prompt == "n":
        logger.error("You have said no. We will not be able to continue")
    else:
        logger.error("You must use 'y' or 'n' when prompted")
        return input_prompt(question)

    return answer


def confirm_prompt(lundata):
    return input_prompt("Are you sure you want to remove LUN %s" % lundata["lun"])


def add_lun(lundata):
    storage_vendor = lundata["vendor"]

    if existing_lun_check(lundata):
        logger.note("%s is already configured. Exiting" % lundata["lun"])
        return

    scsibus = SCSIBus(lundata)
    scsibus.scsi_rescan()

    # This leverages the vendor variable that have already determined and
    # appends it to the method call to ensure we always call the right logic
    # for that vendor
    getattr(vendor(storage_vendor), ("%s_add_lun" % storage_vendor))(lundata)

    if lundata["partition"]:
        precheck = getattr(vendor(storage_vendor), ("%s_is_in_use" % storage_vendor))(lundata)
        if precheck:
            logger.error("LUN Found with previous data. Validate manually")
            return
        else:
            precheck = getattr(vendor(storage_vendor), ("%s_partition" % storage_vendor))(lundata)

    if lundata["clustered"]:
        if lundata["partition"]:
            logger.note(
                "Clustered LVM is in use. Run this tool on all other cluster nodes before "
                "running any LVM commands."
            )
        else:
            logger.note(
                "Clustered LVM is in use. Before utilizing the LUN in LVM or any other "
                "service:\n- Manually create the partition and PV on this node\n- Run this tool on "
                "the other node(s)\n    if this LUN is already present on the other nodes, run: "
                "'partx -a /dev/emcpowerX' on each of those nodes"
            )


def remove_lun(lundata):
    storage_vendor = lundata["vendor"]

    if not existing_lun_check(lundata):
        logger.note("LUN not on server")
        return

    precheck = getattr(vendor(storage_vendor), ("%s_is_in_use" % storage_vendor))(lundata)
    if precheck:
        logger.error("LUN still in use. Exiting")
        return

    logger.debug("Prechecks cleared. Proceeding with removal process")
    if not lundata["force"]:
        prompt = confirm_prompt(lundata)
        if not prompt:
            return

    vendor_removal = getattr(vendor(storage_vendor), ("%s_remove_lun" % storage_vendor))(lundata)
    if vendor_removal[0]:
        scsibus = SCSIBus(lundata)
        removal = scsibus.scsi_remove(vendor_removal[1])
        if removal:
            logger.note("Successfully removed LUN: %s" % lundata["lun"])
            logger.note("Contact the Storage Team to remove LUN %s from this host" % lundata["lun"])
            logger.debug("Running vendor post removal steps")
            post = getattr(vendor(storage_vendor), ("%s_post_removal" % storage_vendor))()
            if not post:
                logger.warn("Post removal work did not complete as expected. Please verify results")
        else:
            logger.error("Error removing disks %s. Please investigate" % vendor_removal[1])


def lun_info(lundata):
    storage_vendor = lundata["vendor"]
    lunid = lundata["lun"]

    if not existing_lun_check(lundata):
        print("Provided ID does not exist on server. Please check your input")

        return
    path = getattr(vendor(storage_vendor), ("%s_get_path" % storage_vendor))()
    mapping = getattr(vendor(storage_vendor), ("%s_get_mapping" % storage_vendor))(lundata["lun"])
    disks = getattr(vendor(storage_vendor), ("%s_get_disks" % storage_vendor))(mapping)
    disklogic = Disk_Logic(path, mapping, lundata)
    print("WWN: %s" % lunid)
    print("Mapping: %s" % disklogic.osdisk)
    print("Vendor: %s" % storage_vendor.upper())
    print("Block Devices: %s" % disks)
    print("LUN Size: %s" % disklogic.lunsize())


def existing_lun_check(lundata):

    storage_vendor = lundata["vendor"]
    lunid = lundata["lun"]
    # This leverages the vendor variable that have already determined and
    # appends it to the method call to ensure we always call the right logic
    # for that vendor
    exists = getattr(vendor(storage_vendor), ("%s_lun_exist" % storage_vendor))(lunid)

    return exists


def scan_unused():
    sbus = SCSIBus({})
    sbus.scsi_rescan()
    sbus.scsiinfo = sbus.get_scsi_info()
    for key, value in sbus.scsiinfo[1].items():
        if value == "EMC":
            logger.info("EMC detected, running powermt config/save")
            EMC({}).configure_powermt()
            break


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


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

    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", "info"],
        help="Task to be done at LUN Level (add, remove, info)",
        dest="action",
    )
    parser.add_option(
        "-i",
        "--lunid",
        action="store",
        help="LUN Identifier (LUNID/WWN) or Device Mapping(emcpowerX) when used with remove action",
        dest="lunid",
    )
    parser.add_option(
        "-w",
        "--writepartition",
        default=False,
        action="store_true",
        help="Write a single, GPT, aligned, full disk partition",
        dest="partition",
    )
    parser.add_option(
        "--nowritelvmlabel",
        default=False,
        action="store_true",
        help="Don't tag partition for LVM (only applicable with --writepartition)",
        dest="lvmtag",
    )
    parser.add_option(
        "--noclvmcheck",
        default=False,
        action="store_true",
        help="Don't check for CLVM, consider server as standalone",
        dest="clustered",
    )
    parser.add_option(
        "-s",
        "--skip_lun_validation",
        help="Skip validity tests for LUN ID",
        action="store_true",
        default=False,
        dest="skip",
    )
    parser.add_option(
        "--scanunused",
        default=False,
        action="store_true",
        help="Rescan unused SCSI bus paths, standalone (default for '-a')",
        dest="scanunused",
    )
    parser.add_option(
        "--scanall",
        default=False,
        action="store_true",
        help="Rescan entire SCSI bus, standalone or with '-a add' - caution, may interrupt I/O",
        dest="scanall",
    )
    parser.add_option(
        "-f",
        "--force",
        help="Skip removal confirmation",
        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",
    )

    return parser


def validate_args(parser):
    valid = True

    main_opts = [
        config.options.lunid,
        config.options.action,
        config.options.scanunused,
        config.options.scanall,
    ]

    if not any(main_opts):
        valid = False
        parser.print_help()
    if not config.options.action and not (config.options.scanunused or config.options.scanall):
        valid = False
        logger.error("An action is required. Please use the '-a/--action' flag")
    if not config.options.lunid and not (config.options.scanunused or config.options.scanall):
        valid = False
        logger.error("A LUNID is required. Please use the '-i/--lunid' flag")
    if config.options.partition and config.options.action != "add":
        valid = False
        logger.error("'-w/--writepartition' can only used when adding a new LUN")
    if config.options.lvmtag and not config.options.partition:
        valid = False
        logger.error("'--nowritelvmlabel' requires the '-w/--writepartition' flag")
    if config.options.scanunused and config.options.scanall:
        valid = False
        logger.error("'--scanunused' and '--scanall' cannot be used together")

    return valid


def main():
    parser = parse_args()
    config.options, _ = parser.parse_args()
    log_level = get_log_level()
    customize_logger(log_level)
    if not validate_args(parser):
        logger.error("Invalid command usage.")
        sys.exit(1)

    # --scanunused or --scanall w/o --action
    if not config.options.action:
        if config.options.scanunused:
            logger.note("Rescanning unused HBA paths and exiting")
            scan_unused()
            sys.exit(0)
        if config.options.scanall:
            logger.note("Rescanning all HBAs and exiting")
            SCSIBus.scanall()
            sys.exit(0)

    try:
        luncore = LUNCore()
        lundata = luncore.dict_generator(
            config.options.lunid,
            config.options.action,
            config.options.skip,
            config.options.partition,
            config.options.lvmtag,
            config.options.clustered,
            config.options.force,
        )
    except ValueError as e:
        print(e)
        sys.exit(1)

    if config.options.action in "add":
        add_lun(lundata)
    if config.options.action in "remove":
        remove_lun(lundata)
    if config.options.action in "info":
        lun_info(lundata)


if __name__ == "__main__":
    signal.signal(signal.SIGINT, sigbye_handler)
    signal.signal(signal.SIGQUIT, sigbye_handler)
    signal.signal(signal.SIGTERM, sigbye_handler)
    main()
