#!/usr/bin/env python

__version__ = '1.0.3'
temp_dir = None

import os
import re
import sys
import shlex
import shutil
import random
import signal
import tarfile
import tempfile
import subprocess

# Conditional imports to support Python 2.4-3.4
try:
    from argparse import ArgumentParser as ArgParser
except ImportError:
    from optparse import OptionParser as ArgParser

try:
    from urllib2 import urlopen
except ImportError:
    from urllib.request import urlopen


def search_for_missing_args(args):
    """Loop through provided command line arguments and attempt to find
    missing responses in "cookie" files on the filesystem. If not running
    automated prompt for the missing arguments
    """

    # File map for argument name to cookie file name
    file_map = {
        'account': 'customer_number',
        'server': 'server_number',
        'location': 'datacenter',
    }

    # These are non-required values that we don't want to prompt for or
    # exit if they aren't available
    skip = ['update_source', 'version']

    for key, value in list(vars(args).items()):
        response = None
        if value is None:
            if key in skip:
                continue
            try:
                response_file = os.path.join(args.source_dir, file_map[key])
                f = open(response_file, 'rb')
                response = f.read().strip()
                f.close()
            except IOError:
                pass
            except Exception:
                e = sys.exc_info()[1]
                err('An unknown error was encountered: %s' % e, 255)

            if args.automated and response is None:
                err('This was to be an automated install but not all required '
                    'arguments were provided or available ("%s")\n' % key, 3)

            while response is None:
                try:
                    response = raw_input('%s: ' % key.title())
                except NameError:
                    response = input('%s: ' % key.title())

            # At this point we should have a response, so set it
            setattr(args, key, response)

    # Ensure we have the datacenter/location lowercased and stripped
    setattr(args, 'location', args.location[:3].lower())

    # Ensure install_dir does not have a trailing slash
    setattr(args, 'install_dir', args.install_dir.rstrip('/'))


def check_perms():
    """Make sure we are running as a root level user"""

    if os.geteuid() != 0:
        err('This script requires root level permissions to operate.\n', 2)


def make_temp_dir():
    """Create the temp dir that will be used for our install tasks
    it will be based in /opt with a prefix of sophos-install-tmp
    such as: /opt/sophos-install-tmpZkG6bE
    """

    global temp_dir
    temp_dir = tempfile.mkdtemp(prefix='sophos-install-tmp', dir='/opt')
    return temp_dir


def retrieve_tar_file(temp_dir, tar_file):
    """Retrieve the tarfile"""

    dest_path = os.path.join(temp_dir, os.path.basename(tar_file))
    try:
        dest = open(dest_path, 'w+b')
        f = urlopen(tar_file)
        shutil.copyfileobj(f, dest, 10240)
    except Exception:
        e = sys.exc_info()[1]
        err('An unknown error was encountered: %s' % e, 255)

    return dest_path


def retrieve_install_options(temp_dir, args):
    """Retrieve the appropriate installOptions file and manipulate the values
    based on supplied arguments
    """

    dest_path = os.path.join(temp_dir, 'installOptions')
    try:
        f = urlopen(args.install_options)
        install_options_src = f.read()

        f.close()
    except Exception:
        e = sys.exc_info()[1]
        err('An unknown error was encountered: %s' % e, 255)

    # Get installOptions into a format we can easily manipulate
    install_options_dict = dict([kv.split('=') for kv in
                                 shlex.split(install_options_src)
                                 if '=' in kv])

    # Set specific options based on runtime config of this script
    install_options_dict.update({
        '--instdir': args.install_dir,
        '--update-cache-path': '%s/update/cache/Primary' % args.install_dir,
        '--enableSavWeb': 'False'
    })

    # This removes install options that we will override later or don't want
    del_keys = ['--automatic', '--ignore-existing-installation',
                '--SavWebPassword', '--SavWebUsername']
    for key in del_keys:
        try:
            del install_options_dict[key]
        except:
            pass

    # If a update_source was provided use it, otherwise update args
    # with the --update-source-path from installOptions
    if args.update_source is not None:
        install_options_dict['--update-source-path'] = args.update_source
    else:
        setattr(args, 'update_source',
                install_options_dict['--update-source-path'])

    # Stick the dictionary back together into a single line string
    install_options = ' '.join(['%s=%s' % kv for kv in
                                list(install_options_dict.items())
                                if kv[1]])

    # Make sure we are overwriting previous installs and forcing an automatic
    # installation
    extra_install_options = [
        '--ignore-existing-installation',
        '--automatic'
    ]
    # Write out the installOptions file
    try:
        f = open(dest_path, 'w+b')
        f.write('%s %s' % (install_options, ' '.join(extra_install_options)))
        f.close()
    except Exception:
        e = sys.exc_info()[1]
        err('An unknown error was encountered: %s' % e, 255)


def extract_tarfile(filename, temp_dir):
    """Extract the tarfile into the temp directory"""

    try:
        tar = tarfile.open(filename, 'r:gz')
        tar.extractall(temp_dir)
    except IOError:
        err('%s could not be found, opened or extracted\n' % filename, 4)
    except Exception:
        e = sys.exc_info()[1]
        err('An unknown error was encountered: %s' % e, 255)


def execute(command, debug=False):
    """Execute a shell command

    If debug is enabled this will Popen will print to stdout and stderr
    """

    if debug:
        stdout = sys.stdout
        stderr = sys.stderr
    else:
        stdout = subprocess.PIPE
        stderr = subprocess.PIPE

    p = subprocess.Popen(command, stdout=stdout,
                         stderr=subprocess.PIPE, shell=True)
    stdout, stderr = p.communicate()

    if p.returncode != 0:
        err('An error occurred while executing:\nCommand: %s\n'
            'Exit Code: %s\nSTDOUT: %s\n\nSTDERR: %s' %
            (command, p.returncode, stdout, stderr), 5)


def configure_sophos(args, temp_dir):
    """Write out the files needed by sophos and configure specific options"""

    try:
        f = open(os.path.join(args.install_dir, 'etc', 'hostname'), 'w+b')
        f.write('%s\n' % args.server)
        f.close()
    except IOError:
        err('Could not write hostname to %s' %
            os.path.join(args.install_dir, 'etc', 'hostname'), 6)
    except Exception:
        e = sys.exc_info()[1]
        err('An unknown error was encountered: %s' % e, 255)

    try:
        f = open(os.path.join(args.install_dir, 'etc', 'description'), 'w+b')
        f.write('%s\n' % args.account)
        f.close()
    except IOError:
        err('Could not write account to %s' %
            os.path.join(args.install_dir, 'etc', 'description'), 7)
    except Exception:
        e = sys.exc_info()[1]
        err('An unknown error was encountered: %s' % e, 255)

    # Starting the sav-web service will enable the web gui with or without
    # a password, so let's generate some random password to prevent access
    # if accidentally enabled
    rand_pass = re.sub('[^\w]+', '', os.urandom(256))[:15]

    savconfig = os.path.join(args.install_dir, 'bin', 'savconfig')

    options = {
        'PrimaryUpdateSourcePath': args.update_source,
        'UpdatePeriodMinutes': args.update_period,
        'TalpaOperations': '-- -open',
        'HttpPassword': rand_pass,
    }

    for option in list(options.items()):
        execute('%s set %s %s' % ((savconfig,) + option))


def restart_sophos():
    """Restart sophos services

    We aren't restarting sav-web as it will start the web interface regardless
    of any specific configuration to not start it
    """
    execute('/etc/init.d/sav-rms restart')
    execute('/etc/init.d/sav-protect restart')


def check_for_dependencies():
    """Look for known dependencies to required for the installation"""
    if not os.path.isfile('/lib/ld-linux.so.2'):
        err('32bit glibc/libc does not appear to be installed, missing '
            '/lib/ld-linux.so.2\n', 8)


def version():
    """Print the version"""
    raise SystemExit(__version__)


def clean_temp_dir():
    """Helper function to clean up the created temp_dir"""
    if temp_dir:
        try:
            shutil.rmtree(temp_dir)
            pass
        except:
            pass


def err(msg, code):
    """Helper function for printing an error message and exiting with a
    specified exit code

    This will also cleanup the temp dir
    """

    clean_temp_dir()

    sys.stderr.write(msg)
    sys.exit(code)


def ctrl_c(signum, frame):
    """Catch Ctrl-C key sequence and shutdown

    This will also cleanup the temp dir
    """
    clean_temp_dir()
    raise SystemExit('\nCancelling...')


def main():
    """Grab command line arguments and stich together all of the functions to
    get sophos installed and running
    """

    signal.signal(signal.SIGINT, ctrl_c)

    parser = ArgParser()
    # Give optparse.OptionParser an `add_argument` method for
    # compatibility with argparse.ArgumentParser
    try:
        parser.add_argument = parser.add_option
    except AttributeError:
        pass

    mirror = 'http://rax.mirror.rackspace.com/segsupport'

    parser.add_argument('--debug', help='Run this application in debug mode',
                        action='store_true', default=False)
    parser.add_argument('--account', help='Numeric account number')
    parser.add_argument('--server', help='Numeric server number')
    parser.add_argument('--location', help='3 character datacenter code')
    parser.add_argument('--install-dir', help='Set the install directory. '
                                              'Default: /opt/sophos-av',
                        default='/opt/sophos-av')
    parser.add_argument('--source-dir', help='Set the source directory to '
                                             'look for response files. '
                                             'Default: /root/.rackspace',
                        default='/root/.rackspace')

    tar_file = '%s/sophos/sophoswithinstallOptionsremoved.tar.gz' % mirror
    parser.add_argument('--tar-file', help='Set the URL of the tarfile.\n'
                                           'Default: %s' % tar_file,
                        default=tar_file)

    install_options = '%s/sophos/installOptions-<location>' % mirror
    parser.add_argument('--install-options',
                        help='Set the URL of the installOptions file. '
                             'Default: %s' % install_options,
                        default=install_options)

    update_period = int(random.randrange(0, 10)) + 5
    parser.add_argument('--update-period', help='Set the update check in '
                                                'period (in minutes). '
                                                'Default %s' % update_period,
                        default=update_period)
    parser.add_argument('--update-source', help='Set the update source URL')

    parser.add_argument('--no-restart', action='store_true', dest='restart',
                        default=True, help='Do not restart sophos after '
                                           'install')
    parser.add_argument('--automated', action='store_true', default=False,
                        help='Whether this is an automated install or not, if '
                             'specified, prompting is disabled and will fail '
                             'if required configurations are unavailable')

    parser.add_argument('--version', action='store_true',
                        help='Show the version number and exit')

    options = parser.parse_args()
    if isinstance(options, tuple):
        args = options[0]
    else:
        args = options
    del options

    # Print the version and exit
    if args.version:
        version()

    search_for_missing_args(args)

    # Replace <location> with the real location in install_options
    setattr(args, 'install_options',
            args.install_options.replace('<location>', args.location))

    check_perms()
    check_for_dependencies()
    temp_dir = make_temp_dir()
    os.environ['TMPDIR'] = temp_dir

    tar_file = retrieve_tar_file(temp_dir, args.tar_file)

    extract_tarfile(tar_file, temp_dir)

    retrieve_install_options(temp_dir, args)

    if args.automated is False:
        sys.stdout.write('The install process will take several minutes to '
                         'complete...\n')
        sys.stdout.write('This script can be executed with --debug to see '
                         'progress\n')
    savupdate_sh = os.path.join(temp_dir, 'sophos-av', 'update',
                                'savupdate.sh')
    execute('%s --minipkg' % savupdate_sh, args.debug)

    configure_sophos(args, temp_dir)

    if args.restart is True:
        restart_sophos()

    # If we made it this far, clean up the temp dir
    clean_temp_dir()


if __name__ == '__main__':
    main()
