#!/usr/bin/python3

# Copyright 2020 Rackspace Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

__version__ = "1.0.5"
temp_dir = None

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

# 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().decode("utf-8")
                f.close()
            except IOError:
                pass
            except Exception as exp:
                e = sys.exc_info()[1]
                traceback.print_exc(file=sys.stdout)
                err("An unknown error was encountered: %s\n" % 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 as exp:
        traceback.print_exc(file=sys.stdout)
        e = sys.exc_info()[1]
        err("An unknown error was encountered: %s\n" % 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 as exp:
        traceback.print_exc(file=sys.stdout)
        e = sys.exc_info()[1]
        err("An unknown error was encountered: %s\n" % e, 255)

    # Get installOptions into a format we can easily manipulate
    ios = install_options_src
    ios = ios.strip("\n".encode())
    string_split_data = ios.split(" ".encode())
    install_options_dict = {}
    for kv in string_split_data:
        kv = kv.decode().split("=")
        if len(kv) == 2:
            install_options_dict.update({kv[0]: kv[1]})

    # 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")
        installOptionsOut = "%s %s" % (install_options, " ".join(extra_install_options))
        f.write(installOptionsOut.encode())
        f.close()
    except Exception as exp:
        traceback.print_exc(file=sys.stdout)
        e = sys.exc_info()[1]
        err("An unknown error was encountered: %s\n" % 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 as exp:
        traceback.print_exc(file=sys.stdout)
        e = sys.exc_info()[1]
        err("An unknown error was encountered: %s\n" % 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")
        args_server = args.server + "\n"
        f.write(args_server.encode())
        f.close()
    except IOError:
        err(
            "Could not write hostname to %s"
            % os.path.join(args.install_dir, "etc", "hostname"),
            6,
        )
    except Exception as exp:
        traceback.print_exc(file=sys.stdout)
        e = sys.exc_info()[1]
        err("An unknown error was encountered: %s\n" % e, 255)

    try:
        f = open(os.path.join(args.install_dir, "etc", "description"), "w+b")

        f.write((args.account + "\n").encode())
        f.close()
    except IOError:
        err(
            "Could not write account to %s"
            % os.path.join(args.install_dir, "etc", "description"),
            7,
        )
    except Exception as exp:
        traceback.print_exc(file=sys.stdout)
        e = sys.exc_info()[1]
        err("An unknown error was encountered: %s\n" % 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(b"[^\w]+", b"", 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
    """

    if os.path.isfile("/usr/bin/systemctl"):
        execute("/usr/bin/systemctl restart sav-rms.service")
        execute("/usr/bin/systemctl restart sav-protect.service")
    elif os.path.isfile("/bin/systemctl"):
        execute("/bin/systemctl restart sav-rms.service")
        execute("/bin/systemctl restart sav-protect.service")
    else:
        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 = "https://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_el8.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>", str(args.location)),
    )

    check_perms()
#    check_for_dependencies()
    temp_dir = make_temp_dir()

    # TMPDIR may not exist, the get() will return None and avoid a KeyError
    old_tmpdir = os.environ.get("TMPDIR")
    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)

    # TMPDIR may not have been set - this will be None if the previous call
    # did not obtain an existing value from the environment
    if old_tmpdir:
        os.environ["TMPDIR"] = old_tmpdir
    else:
        del os.environ["TMPDIR"]

    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()
