Exemplo n.º 1
0
    def get_shell_script(self, cmd_glob, location=None):
        if not location:
            location = self.working_dir + '/kalite'
        cmd_glob += system_script_extension()

        # Find the command
        cmd = glob.glob(location + "/" + cmd_glob)
        if len(cmd) > 1:
            raise CommandError("Multiple commands found (%s)?  Should choose based on platform, but ... how to do in Python?  Contact us to implement this!" % cmd_glob)
        elif len(cmd)==1:
            cmd = cmd[0]
        else:
            cmd = None
            logging.warn("No command found: (%s in %s)" % (cmd_glob, location))
        return cmd
Exemplo n.º 2
0
    def get_shell_script(self, cmd_glob, location=None):
        if not location:
            location = self.working_dir + '/kalite'
        cmd_glob += system_script_extension()

        # Find the command
        cmd = glob.glob(os.path.join(location, "scripts", cmd_glob))
        if len(cmd) > 1:
            raise CommandError("Multiple commands found (%s)?  Should choose based on platform, but ... how to do in Python?  Contact us to implement this!" % cmd_glob)
        elif len(cmd)==1:
            cmd = cmd[0]
        else:
            cmd = None
            logging.warn("No command found: (%s in %s)" % (cmd_glob, location))
        return cmd
Exemplo n.º 3
0
    def handle(self, *args, **options):
        if not options["interactive"]:
            options["username"] = options["username"] or getattr(settings, "INSTALL_ADMIN_USERNAME", None) or get_clean_default_username()
            options["hostname"] = options["hostname"] or get_host_name()

        sys.stdout.write("                                  \n")  # blank allows ansible scripts to dump errors cleanly.
        sys.stdout.write("  _   __  ___    _     _ _        \n")
        sys.stdout.write(" | | / / / _ \  | |   (_) |       \n")
        sys.stdout.write(" | |/ / / /_\ \ | |    _| |_ ___  \n")
        sys.stdout.write(" |    \ |  _  | | |   | | __/ _ \ \n")
        sys.stdout.write(" | |\  \| | | | | |___| | ||  __/ \n")
        sys.stdout.write(" \_| \_/\_| |_/ \_____/_|\__\___| \n")
        sys.stdout.write("                                  \n")
        sys.stdout.write("http://kalite.learningequality.org\n")
        sys.stdout.write("                                  \n")
        sys.stdout.write("         version %s\n" % VERSION)
        sys.stdout.write("                                  \n")

        if sys.version_info >= (2,8) or sys.version_info < (2,6):
            raise CommandError("You must have Python version 2.6.x or 2.7.x installed. Your version is: %s\n" % sys.version_info)

        if options["interactive"]:
            sys.stdout.write("--------------------------------------------------------------------------------\n")
            sys.stdout.write("\n")
            sys.stdout.write("This script will configure the database and prepare it for use.\n")
            sys.stdout.write("\n")
            sys.stdout.write("--------------------------------------------------------------------------------\n")
            sys.stdout.write("\n")
            raw_input("Press [enter] to continue...")
            sys.stdout.write("\n")

        # Tried not to be os-specific, but ... hey. :-/
        if not is_windows() and hasattr(os, "getuid") and os.getuid() == 502:
            sys.stdout.write("-------------------------------------------------------------------\n")
            sys.stdout.write("WARNING: You are installing KA-Lite as root user!\n")
            sys.stdout.write("\tInstalling as root may cause some permission problems while running\n")
            sys.stdout.write("\tas a normal user in the future.\n")
            sys.stdout.write("-------------------------------------------------------------------\n")
            if options["interactive"]:
                if not raw_input_yn("Do you wish to continue and install it as root?"):
                    raise CommandError("Aborting script.\n")
                sys.stdout.write("\n")

        # Check to see if the current user is the owner of the install directory
        if not os.access(BASE_DIR, os.W_OK):
            raise CommandError("You do not have permission to write to this directory!")

        install_clean = not kalite.is_installed()
        database_kind = settings.DATABASES["default"]["ENGINE"]
        database_file = ("sqlite" in database_kind and settings.DATABASES["default"]["NAME"]) or None

        if database_file and os.path.exists(database_file):
            # We found an existing database file.  By default,
            #   we will upgrade it; users really need to work hard
            #   to delete the file (but it's possible, which is nice).
            sys.stdout.write("-------------------------------------------------------------------\n")
            sys.stdout.write("WARNING: Database file already exists! \n")
            sys.stdout.write("-------------------------------------------------------------------\n")
            if not options["interactive"] \
               or raw_input_yn("Keep database file and upgrade to KA Lite version %s? " % VERSION) \
               or not raw_input_yn("Remove database file '%s' now? " % database_file) \
               or not raw_input_yn("WARNING: all data will be lost!  Are you sure? "):
                install_clean = False
                sys.stdout.write("Upgrading database to KA Lite version %s\n" % VERSION)
            else:
                install_clean = True
                sys.stdout.write("OK.  We will run a clean install; \n")
                sys.stdout.write("the database file will be moved to a deletable location.\n")  # After all, don't delete--just move.

        if not install_clean and not database_file and not kalite.is_installed():
            # Make sure that, for non-sqlite installs, the database exists.
            raise Exception("For databases not using SQLIte, you must set up your database before running setup.")

        # Do all input at once, at the beginning
        if install_clean and options["interactive"]:
            if not options["username"] or not options["password"]:
                sys.stdout.write("\n")
                sys.stdout.write("Please choose a username and password for the admin account on this device.\n")
                sys.stdout.write("\tYou must remember this login information, as you will need\n")
                sys.stdout.write("\tto enter it to administer this installation of KA Lite.\n")
                sys.stdout.write("\n")
            (username, password) = get_username_password(options["username"], options["password"])
            email = options["email"]
            (hostname, description) = get_hostname_and_description(options["hostname"], options["description"])
        else:
            username = options["username"] or getattr(settings, "INSTALL_ADMIN_USERNAME", None)
            password = options["password"] or getattr(settings, "INSTALL_ADMIN_PASSWORD", None)
            email = options["email"]  # default is non-empty
            hostname = options["hostname"]
            description = options["description"]

        if username and not validate_username(username):
            raise CommandError("Username must contain only letters, digits, and underscores, and start with a letter.\n")


        ########################
        # Now do stuff
        ########################

        # Move database file (if exists)
        if install_clean and database_file and os.path.exists(database_file):
            # This is an overwrite install; destroy the old db
            dest_file = tempfile.mkstemp()[1]
            sys.stdout.write("(Re)moving database file to temp location, starting clean install.  Recovery location: %s\n" % dest_file)
            shutil.move(database_file, dest_file)

        # Should clean_pyc for (clean) reinstall purposes
        call_command("clean_pyc", interactive=False, verbosity=options.get("verbosity"), path=os.path.join(settings.PROJECT_PATH, ".."))

        # Migrate the database
        call_command("syncdb", interactive=False, verbosity=options.get("verbosity"))
        call_command("migrate", merge=True, verbosity=options.get("verbosity"))

        # Install data
        if install_clean:
            # Create device, load on any zone data
            call_command("generatekeys", verbosity=options.get("verbosity"))
            call_command("initdevice", hostname, description, verbosity=options.get("verbosity"))
            Facility.initialize_default_facility()

        #else:
            # Device exists; load data if required.
            #
            # Hackish, as this duplicates code from initdevice.
            #
            #if os.path.exists(InitCommand.data_json_file):
            #    # This is a pathway to install zone-based data on a software upgrade.
            #    sys.stdout.write("Loading zone data from '%s'\n" % InitCommand.data_json_file)
            #    load_data_for_offline_install(in_file=InitCommand.data_json_file)

        #    confirm_or_generate_zone()

        # Create the admin user
        if password:  # blank password (non-interactive) means don't create a superuser
            admin = get_object_or_None(User, username=username)
            if not admin:
                call_command("createsuperuser", username=username, email=email, interactive=False, verbosity=options.get("verbosity"))
                admin = User.objects.get(username=username)
            admin.set_password(password)
            admin.save()

        # Now deploy the static files
        call_command("collectstatic", interactive=False)

        if not settings.CENTRAL_SERVER:
            # Move scripts
            for script_name in ["start", "stop", "run_command"]:
                script_file = script_name + system_script_extension()
                dest_dir = os.path.join(settings.PROJECT_PATH, "..")
                src_dir = os.path.join(dest_dir, "scripts")
                shutil.copyfile(os.path.join(src_dir, script_file), os.path.join(dest_dir, script_file))
                shutil.copystat(os.path.join(src_dir, script_file), os.path.join(dest_dir, script_file))

            start_script_path = os.path.realpath(os.path.join(settings.PROJECT_PATH, "..", "start%s" % system_script_extension()))

            # Run videoscan, on the distributed server.
            sys.stdout.write("Scanning for video files in the content directory (%s)\n" % settings.CONTENT_ROOT)
            call_command("videoscan")

            # done; notify the user.
            sys.stdout.write("\n")
            if install_clean:
                sys.stdout.write("CONGRATULATIONS! You've finished setting up the KA Lite server software.\n")
                sys.stdout.write("\tPlease run '%s' to start the server,\n" % start_script_path)
                sys.stdout.write("\tthen load one of the following addresses in your browser to complete the configuration:\n")
                for ip in get_ip_addresses():
                    sys.stdout.write("\t\thttp://%s:%d/\n" % (ip, settings.USER_FACING_PORT()))

            else:
                sys.stdout.write("CONGRATULATIONS! You've finished updating the KA Lite server software.\n")
                sys.stdout.write("\tPlease run '%s' to start the server.\n" % start_script_path)
            sys.stdout.write("\n")
def install_from_package(data_json_file, signature_file, zip_file, dest_dir=None, install_files=[]):
    """
    NOTE: This docstring (below this line) will be dumped as a README file.
    Congratulations on downloading KA Lite!  These instructions will help you install KA Lite.
    """
    import glob
    import os
    import shutil
    import sys

    # Make the true paths
    src_dir = os.path.dirname(__file__) or os.getcwd()  # necessary on Windows
    data_json_file = os.path.join(src_dir, data_json_file)
    signature_file = os.path.join(src_dir, signature_file)
    zip_file = os.path.join(src_dir, zip_file)

    # Validate the unpacked files
    for file in [data_json_file, signature_file, zip_file]:
        if not os.path.exists(file):
            raise Exception("Could not find expected file from zip package: %s" % file)

    # get the destination directory
    while not dest_dir or not os.path.exists(dest_dir) or raw_input("%s: Directory exists; install? [Y/n] " % dest_dir) not in ["", "y", "Y"]:
        if dest_dir and raw_input("%s: Directory does not exist; Create and install? [y/N] " % dest_dir) in ["y","Y"]:
            try:
                os.makedirs(os.path.realpath(dest_dir)) # can't use ensure_dir; external dependency.
                break
            except Exception as e:
                sys.stderr.write("Failed to create dest dir (%s): %s\n" % (dest_dir, e))
        dest_dir = raw_input("Please enter the directory where you'd like to install KA Lite (blank=%s): " % src_dir) or src_dir

    # unpack the inner zip to the destination
    system_specific_unzipping(zip_file, dest_dir)
    sys.stdout.write("\n")

    # Copy, so that if the installation fails, it can be restarted
    shutil.copy(data_json_file, os.path.join(dest_dir, "kalite/static/data/"))

    # Run the setup/start scripts
    files = [f for f in glob.glob(os.path.join(dest_dir, "setup*%s" % system_script_extension())) if not "from_zip" in f]
    return_code = os.system('"%s"' % files[0])
    if return_code:
        sys.stderr.write("Failed to set up KA Lite: exit-code = %s" % return_code)
        sys.exit(return_code)
    return_code = os.system('"%s"' % os.path.join(dest_dir, "start%s" % system_script_extension()))
    if return_code:
        sys.stderr.write("Failed to start KA Lite: exit-code = %s" % return_code)
        sys.exit(return_code)

    # move the data file to the expected location
    static_zip_dir = os.path.join(dest_dir, "kalite/static/zip")
    if not os.path.exists(static_zip_dir):
        os.mkdir(static_zip_dir)
    shutil.move(zip_file, static_zip_dir)
    shutil.move(signature_file, static_zip_dir)

    # Remove the remaining install files
    os.remove(data_json_file)  # was copied in earlier
    for f in install_files:
        fpath = os.path.join(src_dir, f)
        if not os.path.exists(fpath):
            continue
        try:
            os.remove(fpath)
            sys.stdout.write("Removed installation file %s\n" % fpath)
        except Exception as e:
            sys.stderr.write("Failed to delete installation file %s: %s\n" % (fpath, e))
Exemplo n.º 5
0
def install_from_package(data_json_file,
                         signature_file,
                         zip_file,
                         dest_dir=None,
                         install_files=[]):
    """
    NOTE: This docstring (below this line) will be dumped as a README file.
    Congratulations on downloading KA Lite!  These instructions will help you install KA Lite.
    """
    import glob
    import os
    import shutil
    import sys

    # Make the true paths
    src_dir = os.path.dirname(__file__) or os.getcwd()  # necessary on Windows
    data_json_file = os.path.join(src_dir, data_json_file)
    signature_file = os.path.join(src_dir, signature_file)
    zip_file = os.path.join(src_dir, zip_file)

    # Validate the unpacked files
    for file in [data_json_file, signature_file, zip_file]:
        if not os.path.exists(file):
            raise Exception(
                "Could not find expected file from zip package: %s" % file)

    # get the destination directory
    while not dest_dir or not os.path.exists(dest_dir) or raw_input(
            "%s: Directory exists; install? [Y/n] " %
            dest_dir) not in ["", "y", "Y"]:
        if dest_dir and raw_input(
                "%s: Directory does not exist; Create and install? [y/N] " %
                dest_dir) in ["y", "Y"]:
            try:
                os.makedirs(os.path.realpath(
                    dest_dir))  # can't use ensure_dir; external dependency.
                break
            except Exception as e:
                sys.stderr.write("Failed to create dest dir (%s): %s\n" %
                                 (dest_dir, e))
        dest_dir = raw_input(
            "Please enter the directory where you'd like to install KA Lite (blank=%s): "
            % src_dir) or src_dir

    # unpack the inner zip to the destination
    system_specific_unzipping(zip_file, dest_dir)
    sys.stdout.write("\n")

    # Copy, so that if the installation fails, it can be restarted
    shutil.copy(data_json_file, os.path.join(dest_dir, "kalite/static/data/"))

    # Run the setup/start scripts
    files = [
        f for f in glob.glob(
            os.path.join(dest_dir, "setup*%s" % system_script_extension()))
        if not "from_zip" in f
    ]
    return_code = os.system('"%s"' % files[0])
    if return_code:
        sys.stderr.write("Failed to set up KA Lite: exit-code = %s" %
                         return_code)
        sys.exit(return_code)
    return_code = os.system(
        '"%s"' % os.path.join(dest_dir, "start%s" % system_script_extension()))
    if return_code:
        sys.stderr.write("Failed to start KA Lite: exit-code = %s" %
                         return_code)
        sys.exit(return_code)

    # move the data file to the expected location
    static_zip_dir = os.path.join(dest_dir, "kalite/static/zip")
    if not os.path.exists(static_zip_dir):
        os.mkdir(static_zip_dir)
    shutil.move(zip_file, static_zip_dir)
    shutil.move(signature_file, static_zip_dir)

    # Remove the remaining install files
    os.remove(data_json_file)  # was copied in earlier
    for f in install_files:
        fpath = os.path.join(src_dir, f)
        if not os.path.exists(fpath):
            continue
        try:
            os.remove(fpath)
            sys.stdout.write("Removed installation file %s\n" % fpath)
        except Exception as e:
            sys.stderr.write("Failed to delete installation file %s: %s\n" %
                             (fpath, e))
Exemplo n.º 6
0
    def handle(self, *args, **options):
        if not options["interactive"]:
            options["username"] = options["username"] or settings.INSTALL_ADMIN_USERNAME or getpass.getuser()
            options["hostname"] = options["hostname"] or get_host_name()

        sys.stdout.write("  _   __  ___    _     _ _        \n")
        sys.stdout.write(" | | / / / _ \  | |   (_) |       \n")
        sys.stdout.write(" | |/ / / /_\ \ | |    _| |_ ___  \n")
        sys.stdout.write(" |    \ |  _  | | |   | | __/ _ \ \n")
        sys.stdout.write(" | |\  \| | | | | |___| | ||  __/ \n")
        sys.stdout.write(" \_| \_/\_| |_/ \_____/_|\__\___| \n")
        sys.stdout.write("                                  \n")
        sys.stdout.write("http://kalite.learningequality.org\n")
        sys.stdout.write("                                  \n")
        sys.stdout.write("         version %s\n" % VERSION)
        sys.stdout.write("                                  \n")

        if sys.version_info >= (2,8) or sys.version_info < (2,6):
            raise CommandError("You must have Python version 2.6.x or 2.7.x installed. Your version is: %s\n" % sys.version_info)

        if options["interactive"]:
            sys.stdout.write("--------------------------------------------------------------------------------\n")
            sys.stdout.write("\n")
            sys.stdout.write("This script will configure the database and prepare it for use.\n")
            sys.stdout.write("\n")
            sys.stdout.write("--------------------------------------------------------------------------------\n")
            sys.stdout.write("\n")
            raw_input("Press [enter] to continue...")
            sys.stdout.write("\n")

        # Tried not to be os-specific, but ... hey. :-/
        if not is_windows() and hasattr(os, "getuid") and os.getuid() == 502:
            sys.stdout.write("-------------------------------------------------------------------\n")
            sys.stdout.write("WARNING: You are installing KA-Lite as root user!\n")
            sys.stdout.write("\tInstalling as root may cause some permission problems while running\n")
            sys.stdout.write("\tas a normal user in the future.\n")
            sys.stdout.write("-------------------------------------------------------------------\n")
            if options["interactive"]:
                if not raw_input_yn("Do you wish to continue and install it as root?"):
                    raise CommandError("Aborting script.\n")
                sys.stdout.write("\n")

        # Check to see if the current user is the owner of the install directory
        current_owner = find_owner(BASE_DIR)
        current_user = getpass.getuser()
        if current_owner != current_user:
            raise CommandError("""You are not the owner of this directory!
    Please copy all files to a directory that you own and then
    re-run this script.""")

        if not os.access(BASE_DIR, os.W_OK):
            raise CommandError("You do not have permission to write to this directory!")

        database_file = settings.DATABASES["default"]["NAME"]
        install_clean = True
        if os.path.exists(database_file):
            # We found an existing database file.  By default,
            #   we will upgrade it; users really need to work hard
            #   to delete the file (but it's possible, which is nice).
            sys.stdout.write("-------------------------------------------------------------------\n")
            sys.stdout.write("WARNING: Database file already exists! \n")
            sys.stdout.write("-------------------------------------------------------------------\n")
            if not options["interactive"] \
               or raw_input_yn("Keep database file and upgrade to KA Lite version %s? " % VERSION) \
               or not raw_input_yn("Remove database file '%s' now? " % database_file) \
               or not raw_input_yn("WARNING: all data will be lost!  Are you sure? "):
                install_clean = False
                sys.stdout.write("Upgrading database to KA Lite version %s\n" % VERSION)

            if install_clean:
                # After all, don't delete--just move.
                sys.stdout.write("OK.  We will run a clean install; \n")
                sys.stdout.write("the database file will be moved to a deletable location.\n")

        # Do all input at once, at the beginning
        if install_clean and options["interactive"]:
            if not options["username"] or not options["password"]:
                sys.stdout.write("\n")
                sys.stdout.write("Please choose a username and password for the admin account on this device.\n")
                sys.stdout.write("\tYou must remember this login information, as you will need\n")
                sys.stdout.write("\tto enter it to administer this installation of KA Lite.\n")
                sys.stdout.write("\n")
            (username, password) = get_username_password(options["username"], options["password"])
            (hostname, description) = get_hostname_and_description(options["hostname"], options["description"])
        else:
            username = options["username"] or settings.INSTALL_ADMIN_USERNAME
            password = options["password"] or settings.INSTALL_ADMIN_PASSWORD
            hostname = options["hostname"]
            description = options["description"]

        if username and not validate_username(username):
            raise CommandError("Username must contain only letters, digits, and underscores, and start with a letter.\n")


        ########################
        # Now do stuff
        ########################

        # Move database file (if exists)
        if install_clean and os.path.exists(database_file):
            # This is an overwrite install; destroy the old db
            dest_file = tempfile.mkstemp()[1]
            sys.stdout.write("(Re)moving database file to temp location, starting clean install.  Recovery location: %s\n" % dest_file)
            shutil.move(database_file, dest_file)

        # Should clean_pyc for (clean) reinstall purposes
        call_command("clean_pyc", interactive=False, verbosity=options.get("verbosity"), path=os.path.join(settings.PROJECT_PATH, ".."))

        # Migrate the database
        call_command("syncdb", interactive=False, verbosity=options.get("verbosity"))
        call_command("migrate", merge=True, verbosity=options.get("verbosity"))

        # Install data
        if install_clean:
            # Create device, load on any zone data
            call_command("generatekeys", verbosity=options.get("verbosity"))
            call_command("initdevice", hostname, description, verbosity=options.get("verbosity"))

        #else:
            # Device exists; load data if required.
            #
            # Hackish, as this duplicates code from initdevice.
            #
            #if os.path.exists(InitCommand.data_json_file):
            #    # This is a pathway to install zone-based data on a software upgrade.
            #    sys.stdout.write("Loading zone data from '%s'\n" % InitCommand.data_json_file)
            #    load_data_for_offline_install(in_file=InitCommand.data_json_file)

        #    confirm_or_generate_zone()
        #    Facility.initialize_default_facility()

        # Create the admin user
        if password:  # blank password (non-interactive) means don't create a superuser
            admin = get_object_or_None(User, username=username)
            if not admin:
                call_command("createsuperuser", username=username, email="*****@*****.**", interactive=False, verbosity=options.get("verbosity"))
                admin = User.objects.get(username=username)
            admin.set_password(password)
            admin.save()


        # Move scripts
        for script_name in ["start", "stop", "run_command"]:
            script_file = script_name + system_script_extension()
            dest_dir = os.path.join(settings.PROJECT_PATH, "..")
            src_dir = os.path.join(dest_dir, "scripts")
            shutil.copyfile(os.path.join(src_dir, script_file), os.path.join(dest_dir, script_file))
            shutil.copystat(os.path.join(src_dir, script_file), os.path.join(dest_dir, script_file))

        start_script_path = os.path.realpath(os.path.join(settings.PROJECT_PATH, "..", "start%s" % system_script_extension()))

        # Run videoscan, on the distributed server.
        if not settings.CENTRAL_SERVER:
            sys.stdout.write("Scanning for video files in the content directory (%s)\n" % settings.CONTENT_ROOT)
            call_command("videoscan")


        # done; notify the user.
        sys.stdout.write("\n")
        if install_clean:
            sys.stdout.write("CONGRATULATIONS! You've finished setting up the KA Lite server software.\n")
            sys.stdout.write("\tPlease run '%s' to start the server,\n" % start_script_path)
            sys.stdout.write("\tthen load one of the following addresses in your browser to complete the configuration:\n")
            for ip in get_ip_addresses():
                sys.stdout.write("\t\thttp://%s:%d/\n" % (ip, settings.user_facing_port()))

        else:
            sys.stdout.write("CONGRATULATIONS! You've finished updating the KA Lite server software.\n")
            sys.stdout.write("\tPlease run '%s' to start the server.\n" % start_script_path)
        sys.stdout.write("\n")
Exemplo n.º 7
0
    def handle(self, *args, **options):
        if not options["interactive"]:
            options["username"] = options["username"] or getattr(settings, "INSTALL_ADMIN_USERNAME", None) or get_clean_default_username()
            options["hostname"] = options["hostname"] or get_host_name()

        print("                                  ")  # blank allows ansible scripts to dump errors cleanly.
        print("  _   __  ___    _     _ _        ")
        print(" | | / / / _ \  | |   (_) |       ")
        print(" | |/ / / /_\ \ | |    _| |_ ___  ")
        print(" |    \ |  _  | | |   | | __/ _ \ ")
        print(" | |\  \| | | | | |___| | ||  __/ ")
        print(" \_| \_/\_| |_/ \_____/_|\__\___| ")
        print("                                  ")
        print("http://kalite.learningequality.org")
        print("                                  ")
        print("         version %s" % VERSION)
        print("                                  ")

        if sys.version_info >= (2,8) or sys.version_info < (2,6):
            raise CommandError("You must have Python version 2.6.x or 2.7.x installed. Your version is: %s\n" % sys.version_info)

        if options["interactive"]:
            print("--------------------------------------------------------------------------------")
            print("This script will configure the database and prepare it for use.")
            print("--------------------------------------------------------------------------------")
            raw_input("Press [enter] to continue...")

        # Tried not to be os-specific, but ... hey. :-/
        # benjaoming: This doesn't work, why is 502 hard coded!? Root is normally
        # '0' And let's not care about stuff like this, people can be free to
        # run this as root if they want :)
        if not is_windows() and hasattr(os, "getuid") and os.getuid() == 502:
            print("-------------------------------------------------------------------")
            print("WARNING: You are installing KA-Lite as root user!")
            print("\tInstalling as root may cause some permission problems while running")
            print("\tas a normal user in the future.")
            print("-------------------------------------------------------------------")
            if options["interactive"]:
                if not raw_input_yn("Do you wish to continue and install it as root?"):
                    raise CommandError("Aborting script.\n")

        # Check to see if the current user is the owner of the install directory
        if not os.access(BASE_DIR, os.W_OK):
            raise CommandError("You do not have permission to write to this directory!")

        install_clean = not kalite.is_installed()
        database_kind = settings.DATABASES["default"]["ENGINE"]
        database_file = ("sqlite" in database_kind and settings.DATABASES["default"]["NAME"]) or None

        if database_file and os.path.exists(database_file):
            # We found an existing database file.  By default,
            #   we will upgrade it; users really need to work hard
            #   to delete the file (but it's possible, which is nice).
            print("-------------------------------------------------------------------")
            print("WARNING: Database file already exists!")
            print("-------------------------------------------------------------------")
            if not options["interactive"] \
               or raw_input_yn("Keep database file and upgrade to KA Lite version %s? " % VERSION) \
               or not raw_input_yn("Remove database file '%s' now? " % database_file) \
               or not raw_input_yn("WARNING: all data will be lost!  Are you sure? "):
                install_clean = False
                print("Upgrading database to KA Lite version %s" % VERSION)
            else:
                install_clean = True
                print("OK.  We will run a clean install; ")
                print("the database file will be moved to a deletable location.")  # After all, don't delete--just move.

        if not install_clean and not database_file and not kalite.is_installed():
            # Make sure that, for non-sqlite installs, the database exists.
            raise Exception("For databases not using SQLite, you must set up your database before running setup.")

        # Do all input at once, at the beginning
        if install_clean and options["interactive"]:
            if not options["username"] or not options["password"]:
                print("Please choose a username and password for the admin account on this device.")
                print("\tYou must remember this login information, as you will need")
                print("\tto enter it to administer this installation of KA Lite.")
            (username, password) = get_username_password(options["username"], options["password"])
            email = options["email"]
            (hostname, description) = get_hostname_and_description(options["hostname"], options["description"])
        else:
            username = options["username"] or getattr(settings, "INSTALL_ADMIN_USERNAME", None)
            password = options["password"] or getattr(settings, "INSTALL_ADMIN_PASSWORD", None)
            email = options["email"]  # default is non-empty
            hostname = options["hostname"]
            description = options["description"]

        if username and not validate_username(username):
            raise CommandError("Username must contain only letters, digits, and underscores, and start with a letter.\n")


        ########################
        # Now do stuff
        ########################

        # Move database file (if exists)
        if install_clean and database_file and os.path.exists(database_file):
            # This is an overwrite install; destroy the old db
            dest_file = tempfile.mkstemp()[1]
            print("(Re)moving database file to temp location, starting clean install.  Recovery location: %s" % dest_file)
            shutil.move(database_file, dest_file)

        # Should clean_pyc for (clean) reinstall purposes
        call_command("clean_pyc", interactive=False, verbosity=options.get("verbosity"), path=os.path.join(settings.PROJECT_PATH, ".."))

        # Migrate the database
        call_command("syncdb", interactive=False, verbosity=options.get("verbosity"))
        call_command("migrate", merge=True, verbosity=options.get("verbosity"))

        # download assessment items
        # This can take a long time and lead to Travis stalling. None of this is required for tests.
        if options['force-assessment-item-dl']:
            call_command("unpack_assessment_zip", settings.ASSESSMENT_ITEMS_ZIP_URL)
        elif not settings.RUNNING_IN_TRAVIS and options['interactive']:
            print("\nStarting in version 0.13, you will need an assessment items package in order to access many of the available exercises.")
            print("If you have an internet connection, you can download the needed package. Warning: this may take a long time!")
            print("If you have already downloaded the assessment items package, you can specify the file in the next step.")
            print("Otherwise, we will download it from {url}.".format(url=settings.ASSESSMENT_ITEMS_ZIP_URL))

            if raw_input_yn("Do you wish to download the assessment items package now?"):
                ass_item_filename = settings.ASSESSMENT_ITEMS_ZIP_URL
            elif raw_input_yn("Have you already downloaded the assessment items package?"):
                ass_item_filename = get_assessment_items_filename()
            else:
                ass_item_filename = None

            if not ass_item_filename:
                logging.warning("No assessment items package file given. You will need to download and unpack it later.")
            else:
                call_command("unpack_assessment_zip", ass_item_filename)
        else:
            logging.warning("No assessment items package file given. You will need to download and unpack it later.")


        # Individually generate any prerequisite models/state that is missing
        if not Settings.get("private_key"):
            call_command("generatekeys", verbosity=options.get("verbosity"))
        if not Device.objects.count():
            call_command("initdevice", hostname, description, verbosity=options.get("verbosity"))
        if not Facility.objects.count():
            Facility.initialize_default_facility()

        # Install data
        # if install_clean:
        #     # Create device, load on any zone data
        #     call_command("generatekeys", verbosity=options.get("verbosity"))
        #     call_command("initdevice", hostname, description, verbosity=options.get("verbosity"))
        #     Facility.initialize_default_facility()

        #else:
            # Device exists; load data if required.
            #
            # Hackish, as this duplicates code from initdevice.
            #
            #if os.path.exists(InitCommand.data_json_file):
            #    # This is a pathway to install zone-based data on a software upgrade.
            #    print("Loading zone data from '%s'\n" % InitCommand.data_json_file)
            #    load_data_for_offline_install(in_file=InitCommand.data_json_file)

        #    confirm_or_generate_zone()

        # Create the admin user
        if password:  # blank password (non-interactive) means don't create a superuser
            admin = get_object_or_None(User, username=username)
            if not admin:
                call_command("createsuperuser", username=username, email=email, interactive=False, verbosity=options.get("verbosity"))
                admin = User.objects.get(username=username)
            admin.set_password(password)
            admin.save()

        # Now deploy the static files
        call_command("collectstatic", interactive=False)

        if not settings.CENTRAL_SERVER:
            # Move scripts
            for script_name in ["start", "stop", "run_command"]:
                script_file = script_name + system_script_extension()
                dest_dir = os.path.join(settings.PROJECT_PATH, "..")
                src_dir = os.path.join(dest_dir, "scripts")
                shutil.copyfile(os.path.join(src_dir, script_file), os.path.join(dest_dir, script_file))
                try:
                    shutil.copystat(os.path.join(src_dir, script_file), os.path.join(dest_dir, script_file))
                except OSError:  # even if we have write permission, we might not have permission to change file mode
                    print("WARNING: Unable to set file permissions on %s! " % script_file)

            kalite_executable = 'kalite'
            if not spawn.find_executable('kalite'):
                if os.name == 'posix':
                    start_script_path = os.path.realpath(os.path.join(settings.PROJECT_PATH, "..", "bin", kalite_executable))
                else:
                    start_script_path = os.path.realpath(os.path.join(settings.PROJECT_PATH, "..", "bin", "windows", "kalite.bat"))
            else:
                start_script_path = kalite_executable

            # Run videoscan, on the distributed server.
            print("Scanning for video files in the content directory (%s)" % settings.CONTENT_ROOT)
            call_command("videoscan")

            # done; notify the user.
            print("CONGRATULATIONS! You've finished setting up the KA Lite server software.")
            print("You can now start KA Lite with the following command:\n\n\t%s start\n\n" % start_script_path)