protected static function remove_excess_backups_from_directory($course, $now) {
        $config = get_config('backup');
        $dir = $config->backup_auto_destination;

        $isnotvaliddir = !file_exists($dir) || !is_dir($dir) || !is_writable($dir);
        if ($isnotvaliddir) {
            mtrace('Error: ' . $dir . ' does not appear to be a valid directory');
            return false;
        }

        // Calculate backup filename regex, ignoring the date/time/info parts that can be
        // variable, depending of languages, formats and automated backup settings.
        $filename = backup::FORMAT_MOODLE . '-' . backup::TYPE_1COURSE . '-' . $course->id . '-';
        $regex = '#' . preg_quote($filename, '#') . '.*\.mbz$#';

        // Store all the matching files into filename => timemodified array.
        $backupfiles = array();
        foreach (scandir($dir) as $backupfile) {
            // Skip files not matching the naming convention.
            if (!preg_match($regex, $backupfile)) {
                continue;
            }

            // Read the information contained in the backup itself.
            try {
                $bcinfo = backup_general_helper::get_backup_information_from_mbz($dir . '/' . $backupfile);
            } catch (backup_helper_exception $e) {
                mtrace('Error: ' . $backupfile . ' does not appear to be a valid backup (' . $e->errorcode . ')');
                continue;
            }

            // Make sure this backup concerns the course and site we are looking for.
            if ($bcinfo->format === backup::FORMAT_MOODLE &&
                    $bcinfo->type === backup::TYPE_1COURSE &&
                    $bcinfo->original_course_id == $course->id &&
                    backup_general_helper::backup_is_samesite($bcinfo)) {
                $backupfiles[$bcinfo->backup_date] = $backupfile;
            }
        }

        $backupstodelete = self::get_backups_to_delete($backupfiles, $now);
        if ($backupstodelete) {
            foreach ($backupstodelete as $backuptodelete) {
                unlink($dir . '/' . $backuptodelete);
            }
            mtrace('Deleted ' . count($backupstodelete) . ' old backup file(s) from external directory');
            return true;
        } else {
            return false;
        }
    }