#! /usr/bin/env python
import getopt
import os
import re
import sys
import uuid
import isi.hw.fw.modules.epost as epost
import isi.app.lib.procs as procs
import isi.sys.disk as disk
import zipfile

mesh = disk.mesh

GPART_CMD = '/sbin/gpart'
MOUNT_MSDOS_CMD = '/sbin/mount_msdosfs'
UMOUNT_CMD = '/sbin/umount'
NEWFS_MSDOS_CMD = '/sbin/newfs_msdos'
MKDIR_CMD = '/bin/mkdir'
CDESEXPUTIL = '/usr/bin/isi_hwtools/isi_cdesexputil'
FCBVPDTOOL = '/usr/bin/isi_hwtools/isi_fcb_vpd_tool'

EPOST_MOUNT = '/EPOST'
FW_DIR = 'EMC'
FW_PART_LABEL = 'emc-fw'
PN_KEY = 'EMC_TLA_PN'

SYS_CONFIG = '/etc/isilon_system_config'

EP = 'EP'
DE = 'DE'

EPOST_DEVICE = "ada0"

def get_epost_partition():
    partition = None
    providers = filter(lambda x: x.name == EPOST_DEVICE,
                    mesh.disk_providers)
    for provider in providers:
        pg = provider.partition_geom
        for part in pg.providers:
            if part.label == FW_PART_LABEL:
                partition = part.name
                break
    return partition

# copied from isi_create_firmware_package (firmware-packages repo)
def unzip(zpkg, dest_dir):
    zf = zipfile.ZipFile(zpkg)
    zf.extractall(dest_dir)
    zf.close()

def unzip_fw_bundle(path):
    result = 0
    tmp_dir = '/tmp/%s' % uuid.uuid4()
    fw_dst = os.path.join(EPOST_MOUNT, FW_DIR)
    fw_src_emc = os.path.join(tmp_dir, FW_DIR)
    unzip(path, tmp_dir)
    cmd = 'cp -r %s/* %s' % (fw_src_emc, fw_dst)
    error, output = procs.get_cmd_output(cmd)
    if error:
        print 'Unable to cp files from %s to %s' % (fw_src_emc, fw_dst)
        return 1
    cmd = 'rm -rf %s' % tmp_dir
    if error:
        print 'Unable to rm files from %s' % tmp_dir
    return result

def check_fw_partition():
    exists = False
    providers = filter(lambda x: x.name == EPOST_DEVICE,
                    mesh.disk_providers)
    for provider in providers:
        pg = provider.partition_geom
        for part in pg.providers:
            if part.label == FW_PART_LABEL:
                partition = part.name
                exists = True
                break
    return exists

def wipe_fw_partition(dev):
    result = 1
    index = None
    providers = filter(lambda x: x.name in [dev], mesh.disk_providers)
    for provider in providers:
        pg = provider.partition_geom
        for part in pg.providers:
            if part.label == FW_PART_LABEL:
                config = part.config
                index = config.get('index')
                cmd = '%s delete -i %s %s' % (GPART_CMD, index, dev)
                error, output = procs.get_cmd_output(cmd)
                if not error:
                    result = 0
                else:
                    print 'Unable to delete index %s from %s' % (index, dev)
                break
    return result


CDES_RE = re.compile('.*EMA Expander Firmware:\s+(?P<fw>.*)')

def dump_devices():
    nt = get_node_type()
    fw_dict = epost.get_epost_firmware()
    # CDES
    cmd = '%s -q' % CDESEXPUTIL
    err, out = procs.get_cmd_output(cmd)
    match = CDES_RE.search('\n'.join(out), re.M)
    if match:
        fw_dict['CDES FIRMWARE'] = match.group('fw')
    else:
        fw_dict['CDES FIRMWARE'] = None
    # now that we gathered all the firmware components, do a whole bunch of
    # fidgeting to match the naming convention used in the firmware manifest
    # (for ease of parsing)
    if 'BMC Boot Block' in fw_dict:
        try: fw_dict.pop('BMC BB')
        except: pass
        try: fw_dict.pop('BMC ADPT')
        except: pass
    if 'BMC Main App' in fw_dict:
        try: fw_dict.pop('BMC MAIN')
        except: pass
    if 'CMD Bundle Image 1' in fw_dict:
        try: fw_dict.pop('CMDAPP');
        except: pass
        try: fw_dict.pop('CMDBOOT')
        except: pass
        try: fw_dict.pop('CMDTABLE')
        except: pass
    # confirmed with GHE, INTELNIC is for firmware validation test
    try: fw_dict.pop('INTELNIC')
    except: pass
    # pop off peer SP cmd version
    try: fw_dict.pop('Peer SP CMD')
    except: pass
    # VRD components show up in both in FRU DevID 0 and the master device list
    # The naming maps as follows:
    # +------------------------------------+-----------+-----------+--------------+
    # | Master Dev list                    | FRU 0     | Manifest  | File name    |
    # +------------------------------------+-----------+-----------+--------------+
    # | CPU VRD (Intersil)                 | CPU0VRD   | VRD Image | emc_c_vrd0_..|
    # | CPU VRD (ST Micro)                 |           |           |              |
    # +------------------------------------+-----------+-----------+--------------+
    # | Memory Channels 0/1 VRD (Intersil) | C0M01VRD  | VRD Image | emc_c_vrd1_..|
    # | Memory Channels 0/1 VRD (ST Micro) |           |           |              |
    # +------------------------------------+-----------+-----------+--------------+
    # | Memory Channels 2/3 VRD (ST Micro) | C0M23VRD  | VRD Image | emc_c_vrd2_..|
    # | Memory Channels 2/3 VRD (Intersil) |           |           |              |
    # +------------------------------------+-----------+-----------+--------------+
    # Since the naming in the manifest doesn't distinguish very well, we
    # need to look at the file name
    # Picking a naming convention of emc_c_vrd0.. == VRD Image 0, etc
    fru_vrd_names = [('CPU0VRD', 'VRD Image 0'),
                     ('C0M01VRD', 'VRD Image 1'),
                     ('C0M23VRD', 'VRD Image 2')]
    # clean up the redundancy
    for fruname, outname in fru_vrd_names:
        if fruname in fw_dict and outname in fw_dict:
            fw_dict.pop(fruname)

    # actually print the firmware versions
    max_len = len(max(fw_dict.keys(), key=len)) + 1
    for i, key in enumerate(sorted(fw_dict.keys())):
        print('%2d) %-*s: %s' % (i + 1, max_len, key, fw_dict[key]))
    return 0

def check_fw_file(path):
    ntype = get_node_type()
    regex = re.compile('.*%s.*' % ntype)
    match = regex.match(path)
    if not match:
        print('expected firmware file for %s, got %s' % (ntype, path))
        sys.exit(1)

def get_node_type():
    try:
        with open(SYS_CONFIG, 'r') as f:
            config = f.readline().rstrip('\n')
    except IOError as e:
        # try to read eeprom
        regex = re.compile(".*%s.*\['(?P<pn>.*)'\].*" % PN_KEY)
        cmd = '%s read %s' % (FCBVPDTOOL, PN_KEY)
        err, out = procs.get_cmd_output(cmd)
        match = regex.search('\n'.join(out), re.M)
        if match:
            config = match.group('pn')
        else:
            print('failed to get config number %s and eeprom' % SYS_CONFIG)
            sys.exit(1)
    if not config:
        print('failed to read config number from %s' % SYS_CONFIG)
        sys.exit(1)
    if re.match(r'110-385', config):
        return EP
    if re.match(r'110-365', config):
        return DE
    print('unable to determine node type from %s' % config)
    sys.exit(1)

def usage(rc=0, msg=None):
    if msg:
        print(msg)
    print('Usage: %s [OPTION]' % os.path.basename(sys.argv[0]))
    print('''
    -p, --path=FILE     firmware file to load
    -d, --delete        delete firmware partition
    -s, --show          show firware versions
    -t, --type          show node type
    -h, --help          show this help menu
    ''')
    sys.exit(rc)

def main(args):
    try:
        opts, args = getopt.getopt(args, 'hp:sdt',
            ['help', 'path=', 'show', 'delete', 'type'])
    except getopt.GetoptError as err:
        usage(rc=1, msg=str(err))
    path = None
    for o, a in opts:
        if o in ('-p, --path'):
            path = a
        elif o in ('-s', '--show'):
            return dump_devices()
        elif o in ('-d', '--delete'):
            dev = 'ada0'
            if wipe_fw_partition(dev):
                print('Unable to wipe FW partition')
                return 1
            print('Succesfully deleted FW partition')
            return 0
        elif o in ('-t', '--type'):
            nt = get_node_type()
            print('node type: %s' % nt)
            sys.exit(0)
        elif o in ('-h', '--help'):
            usage()
        else:
            assert False, 'unhandled option'
    if not path:
        usage()
    check_fw_file(path)
    dev = EPOST_DEVICE
    if check_fw_partition():
        if wipe_fw_partition(dev):
            print 'Unable to wipe FW partition'
            return 1
    # Create FAT32 partition on vault drive
    cmd = '%s add -t mbr -l %s -s 8G %s' % (GPART_CMD, FW_PART_LABEL, dev)
    error, output = procs.get_cmd_output(cmd)
    if error:
        print 'Unable to create MBR partition on %s' % dev
        return 1
    # Get MBR partition
    mesh.refresh()
    mbr_partition = get_epost_partition()
    if mbr_partition is None:
        print 'Unable to get MBR partition on %s' % dev
        return 1
    # Newfs FAT32 partitionFAT32
    cmd = '%s -F32 %s' % (NEWFS_MSDOS_CMD, mbr_partition)
    error, output = procs.get_cmd_output(cmd)
    if error:
        print 'Error running newfs_msdos on %s' % mbr_partition
        return 1
    # Create mount point
    # XXX FIXME Don't always create
    # XXX FIXME Unmount if already mounted
    cmd = '%s -p %s' % (MKDIR_CMD, EPOST_MOUNT)
    error, output = procs.get_cmd_output(cmd)
    if error:
        print 'Unable to mkdir %s' % EPOST_MOUNT
        return 1
    # Mount Fat32 Partition
    cmd = '%s /dev/%s %s' % (MOUNT_MSDOS_CMD, mbr_partition, EPOST_MOUNT)
    error, output = procs.get_cmd_output(cmd)
    if error:
        print output
        print 'Unable to mount %s on %s' % (mbr_partition, EPOST_MOUNT)
        return 1
    # Create /EMC directory
    cmd = '%s %s/%s' % (MKDIR_CMD, EPOST_MOUNT, FW_DIR)
    error, output = procs.get_cmd_output(cmd)
    if error:
        print 'Unable to mkdir %s/%s' % (EPOST_MOUNT, FW_DIR)
        return 1
    # Unpack tarball in directory
    if unzip_fw_bundle(path):
        print 'Unable to unpack FW bundle located at %s' % path
        return 1
    # Unmount FS
    cmd = '%s %s' % (UMOUNT_CMD, EPOST_MOUNT)
    error, output = procs.get_cmd_output(cmd)
    if error:
        print 'Unable to umount %s' % EPOST_MOUNT
        return 1
    return 0

if __name__ == '__main__':
    main(sys.argv[1:])
