#!/usr/bin/python
import errno
import glob
import logging
import optparse
import os
import re
import readline
import subprocess
import sys
import urllib2
import urlparse

import isi.app.lib.kenv as kenv
import isi.hw.hal as hal
import isi.hw.version as version
import isi.sys.bootdisk as bootdisk
import isi.sys.disk as disk
import isi.sys.geom as geom
import isi.sys.update.handlers as handlers

FLASHDISK = '/dev/md0'
DEFAULT_DST = '/usr/install.tar.gz'

KENV_INSTALLFILE = "isilon_installfile"
KENV_ACSFILE = "isilon_acsfile"
KENV_HWATTRFILE = "isilon_hwattrfile"

INSTALLFILE_PROMPT = "Input an install package"
ACSFILE_PROMPT = "Input location for the ACS configuration file"
HWATTR_PROMPT = "Input location for the hardware configuration file"

LOGGER = logging.getLogger("isi_flashdisk_start")
LOGGER.setLevel(logging.WARN)


def match_path(text, state):
    """
    Readline callback function, attempts to complete or return a list of files.
    """
    if os.path.exists(text):
        matches = sorted([path for path in os.listdir(text)
                          if path not in ('.', '..')])
    else:
        if not glob.has_magic(text):
            text += '*'
        matches = glob.glob(text)
    return matches[state]


def setup_gmirror():
    """
    Backup providers and recreate the GPT partitions and mirrors for the
    bootdisks.
    """
    backups = dict()
    wipe = True
    skip = list()

    # Back up any providers in default_save_providers
    bootdisk.backup_providers(backups)
    try:
        # init providers
        bootdisk.init_providers(wipe=wipe, skip=skip)
    finally:
        # Restore changes to save_providers if we wiped everything
        bootdisk.restore_providers(backups)


def memdisk_mfg(build):
    handlers.create_handler(handlers.MEMDISK_REIMAGE, b=build, f=True, i=False)
    return "MEMDISK MFG fallthrough"


def memdisk_reimage(build, args):
    if bootdisk.booted_from_reimage_flash():
        subprocess.check_call(['/usr/bin/isi_vpd_pull', '--reImage'])
        hal.reInitialize()
        if hal.supportsCto():
            subprocess.call(['/usr/bin/isi_inventory_tool',
                             '--startUp', '--reImage'])
            hal.reInitialize()

    option_dict = handlers.default_options()
    option_dict["no_reboot"] = args.no_reboot
    handlers.create_handler(handlers.MEMDISK_REIMAGE, b=build, f=args.force,
                            i=args.ignoremd5, options=option_dict)
    return "MEMDISK REIMAGE fallthrough"

def pxe_reimage(build, args):
    if bootdisk.booted_from_reimage_flash():
        subprocess.check_call(['/usr/bin/isi_vpd_pull', '--reImage'])
        hal.reInitialize()
        if hal.supportsCto():
            subprocess.call(['/usr/bin/isi_inventory_tool',
                             '--startUp', '--reImage'])
            hal.reInitialize()

    option_dict = handlers.default_options()
    option_dict["no_reboot"] = args.no_reboot
    handlers.create_handler(handlers.PXE_REIMAGE, b=build, f=args.force,
                            i=args.ignoremd5, options=option_dict)
    return "PXE REIMAGE fallthrough"

def memdisk_update(build, args):
    option_dict = handlers.default_options()
    option_dict["no_reboot"] = args.no_reboot
    handlers.create_handler(handlers.MEMDISK_UPDATE, b=build, f=args.force,
                            i=args.ignoremd5, options=option_dict)
    return "MEMDISK UPDATE fallthrough"

def pxe_update(build, args):
    option_dict = handlers.default_options()
    option_dict["no_reboot"] = args.no_reboot
    handlers.create_handler(handlers.PXE_UPDATE, b=build, f=args.force,
                            i=args.ignoremd5, options=option_dict)
    return "PXE UPDATE fallthrough"

def http_handler(parseresult):
    url = parseresult.geturl()
    try:
        req = urllib2.urlopen(url)
    except urllib2.HTTPError as ex:
        sys.stderr.write("%s: %s: %s" % (url, ex.code, ex.msg))
        return
    return req.geturl()


def tftp_handler(parseresult):
    server = parseresult.netloc
    src = parseresult.path
    cmd = ("tftp", server)
    req = "\n".join(["mode binary",
                     "get %s %s" % (src, DEFAULT_DST)])
    fin_re = re.compile(r"Received \d+ bytes")

    LOGGER.info("Downloading %s from %s", src, server)
    proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    (stdout, _) = proc.communicate(req)
    retcode = proc.poll()

    lastline = stdout.splitlines()[-1]
    match = fin_re.match(lastline)
    if retcode or not match:
        raise StandardError(lastline)

    LOGGER.info(lastline)
    LOGGER.info("Finished %s", DEFAULT_DST)
    return DEFAULT_DST


def getmethefile(cli_prompt, default=None):
    """
    Get the installfile from the commandline and return it.
    """
    thefile = None
    while not thefile:
        compdelims = readline.get_completer_delims()
        readline.parse_and_bind("tab: complete")
        readline.set_completer_delims(" ")
        readline.set_completer(match_path)

        print cli_prompt
        if default:
            sys.stdout.write("[%s]: " % (default,))
        thefile = raw_input().strip() or default

        readline.set_completer_delims(compdelims)
        readline.set_completer(None)

    return thefile


def otherfile_handlers(prompt, cli_value, kenv_label=None, force=False):
    thefile = None

    if cli_value:
        thefile = cli_value
    elif kenv_label:
        thefile = kenv.kenv_get(kenv_label)

    if not thefile or not force:
        thefile = getmethefile(prompt, thefile)

    return thefile


def installfile_handler(args):
    """
    Some protocols are handled in a special manner, otherwise it is passed to
    the reimage handler which will work for local/http/ftp files
    """
    installfile = otherfile_handlers(INSTALLFILE_PROMPT, args.build,
                                     KENV_INSTALLFILE, force=args.force)

    if os.path.exists(installfile):
        return installfile

    # Python 2.6 urlparse doesn't understand that tftp is a network URL
    urlparse.uses_netloc.append('tftp')

    # XXX figure out how to make errors inside the handler recoverable
    # some refactoring is needed to go back to input_installfile at the top
    parsed = urlparse.urlparse(installfile)
    if parsed.scheme == "tftp":
        handled_installfile = tftp_handler(parsed)
    elif parsed.scheme == "http":
        handled_installfile = http_handler(parsed)
    else:
        LOGGER.info("No handler found: %s", installfile)

    if not handled_installfile:
        raise StandardError("No installfile was returned by any handler!")

    return handled_installfile


def main(args):
    """
    Magic!
    """
    # XXX isi.sys.update does not unmount before starting a new update
    bootdisk.umount("/keystore")
    bootdisk.umount("/usr/update/root")
    bootdisk.umount("/usr/update/var")

    # Perform setup for the disks
    setup_gmirror()

    # Do stuff with the disks
    flashtype = None
    if args.build:
        if args.update:
            flashtype = disk.FLASHTYPE_UPDATE
        else:
            flashtype = disk.FLASHTYPE_REIMAGE
    else:
        flashtype = disk.flashtype(FLASHDISK)

    if not flashtype:
        return "No flashtype detected"
    if flashtype not in disk.FLASHTYPES:
        return "Flashtype is not valid: %s" % (flashtype,)
    LOGGER.debug("flashtype: %s", flashtype)

    if flashtype in (disk.FLASHTYPE_UPDATE, disk.FLASHTYPE_REIMAGE):
        # Create a temp file to let the boot system know we're reimaging
        open(bootdisk.FLASH_REIMAGE_MARKER, 'a').close()
        installfile = installfile_handler(args)

    # Handle the flashtype actions
    # XXXBSDMERGE recovery, manufacturing, etc. need to be reimplemented!
    if flashtype == disk.FLASHTYPE_UPDATE:
        return memdisk_update(installfile, args)
    elif flashtype == disk.FLASHTYPE_REIMAGE:
        if bootdisk.future_system_is_geom():
            bootdisk.mount_keystore()
        # XXX Figure out how to wire these up
        #acsfile = otherfile_handlers(prompt=ACSFILE_PROMPT, cli_value=args.acs,
        #                             kenv_label=KENV_ACSFILE, force=args.force)
        #hwattrfile = otherfile_handlers(prompt=HWATTR_PROMPT,
        #                                cli_value=args.hwattr,
        #                                kenv_label=KENV_HWATTRFILE,
        #                                force=args.force)
        if args.pxe:
            return pxe_reimage(installfile, args)
        else:
            return memdisk_reimage(installfile, args)
    else:
        # XXX handle error case
        return "No supported isilon_flashtype info found"


def getargs(args):
    argparser = optparse.OptionParser()
    argparser.add_option(
        '-b', '--build',
        default=None,
        help="The file or location to use for the reimage.")
    argparser.add_option(
        '--acs',
        default=None,
        help="The file or location to use for downloading the ACS file.")
    argparser.add_option(
        '--hwattr',
        default=None,
        help="The file or location to use for downloading the hwattribs file.")
    argparser.add_option(
        '--pxe',
        action="store_true",
        help="PXE boot, assumes reboot at end of install vs halt")
    argparser.add_option(
        '-u', '--update',
        action="store_true",
        help="Update the node instead of reimaging.")
    argparser.add_option(
        '-f', '--force',
        action="store_true",
        help="Force the install of the build without confirmation.")
    argparser.add_option(
        '-i', '--ignoremd5',
        action="store_true",
        help="Ignore the MD5 check for the build.")
    argparser.add_option(
        '--no-reboot',
        action="store_true",
        help="do not reboot node when done with reimage")
    argparser.add_option(
        '-F', '--logfile',
        help="A file path to write logging output to")
    argparser.add_option(
        '-L', '--loglevel',
        default="INFO",
        help="The logging level to print. "
             "The default is %default")
    (opts, _) = argparser.parse_args(args)
    loglevel = getattr(logging, opts.loglevel.upper())
    formatter = logging.Formatter(
        r'%(asctime)-15s %(levelname)s:%(name)s:%(funcName)s:%(lineno)d: '
        '%(message)s')
    handler = logging.StreamHandler()
    handler.setFormatter(formatter)
    handler.setLevel(loglevel)
    LOGGER.setLevel(loglevel)
    LOGGER.addHandler(handler)
    return opts


if __name__ == "__main__":
    exit(main(getargs(sys.argv[1:])))
