public static function get_automated_backup_state($rundirective = self::RUN_ON_SCHEDULE) {
        global $DB;

        $config = get_config('backup');
        $active = (int)$config->backup_auto_active;
        $weekdays = (string)$config->backup_auto_weekdays;

        // In case of automated backup also check that it is scheduled for at least one weekday.
        if ($active === self::AUTO_BACKUP_DISABLED ||
                ($rundirective == self::RUN_ON_SCHEDULE && $active === self::AUTO_BACKUP_MANUAL) ||
                ($rundirective == self::RUN_ON_SCHEDULE && strpos($weekdays, '1') === false)) {
            return self::STATE_DISABLED;
        } else if (!empty($config->backup_auto_running)) {
            // Detect if the backup_auto_running semaphore is a valid one
            // by looking for recent activity in the backup_controllers table
            // for backups of type backup::MODE_AUTOMATED
            $timetosee = 60 * 90; // Time to consider in order to clean the semaphore
            $params = array( 'purpose'   => backup::MODE_AUTOMATED, 'timetolook' => (time() - $timetosee));
            if ($DB->record_exists_select('backup_controllers',
                "operation = 'backup' AND type = 'course' AND purpose = :purpose AND timemodified > :timetolook", $params)) {
                return self::STATE_RUNNING; // Recent activity found, still running
            } else {
                // No recent activity found, let's clean the semaphore
                mtrace('Automated backups activity not found in last ' . (int)$timetosee/60 . ' minutes. Cleaning running status');
                backup_cron_automated_helper::set_state_running(false);
            }
        }
        return self::STATE_OK;
    }