#!/usr/bin/env php
<?php
namespace Misuzu;

use stdClass;
use Exception;

require_once __DIR__ . '/../misuzu.php';

$schedTasks = [];
$runSlow = false; // by what metric? i made it up.

function msz_sched_task_sql(string $name, bool $slow, string $command): void {
    global $schedTasks, $runSlow;

    if($slow && !$runSlow)
        return;

    $schedTasks[] = $task = new stdClass;
    $task->name = $name;
    $task->type = 'sql';
    $task->command = $command;
}

function msz_sched_task_func(string $name, bool $slow, callable $command): void {
    global $schedTasks, $runSlow;

    if($slow && !$runSlow)
        return;

    $schedTasks[] = $task = new stdClass;
    $task->name = $name;
    $task->type = 'func';
    $task->command = $command;
}

for($i = 1; $i < count($argv); ++$i) {
    $argvi = $argv[$i];
    if($argvi === 'slow')
        $runSlow = true;
    else die('Unknown argument specified.' . PHP_EOL);
}

if($runSlow)
    echo 'Also running slow tasks!' . PHP_EOL;
else
    echo 'Only running quick tasks!' . PHP_EOL;
echo PHP_EOL;

msz_sched_task_sql('Ensure main role exists.', true,
    'INSERT IGNORE INTO msz_roles (role_id, role_name, role_hierarchy, role_colour, role_description, role_created) VALUES (1, "Member", 1, 1073741824, NULL, NOW())');

msz_sched_task_sql('Ensure all users have the main role.', true,
    'INSERT INTO msz_user_roles (user_id, role_id) SELECT user_id, 1 FROM msz_users AS u WHERE NOT EXISTS (SELECT 1 FROM msz_user_roles AS ur WHERE role_id = 1 AND u.user_id = ur.user_id)');

msz_sched_task_sql('Ensure all display_role field values are correct with msz_user_roles.', true,
    'UPDATE msz_users AS u SET display_role = (SELECT ur.role_id FROM msz_user_roles AS ur LEFT JOIN msz_roles AS r ON r.role_id = ur.role_id WHERE ur.user_id = u.user_id ORDER BY role_hierarchy DESC LIMIT 1) WHERE NOT EXISTS (SELECT 1 FROM msz_user_roles AS ur WHERE ur.role_id = u.display_role AND ur.user_id = u.user_id)');

msz_sched_task_sql('Remove expired sessions.', false,
    'DELETE FROM msz_sessions WHERE session_expires < NOW()');

msz_sched_task_sql('Remove old password reset tokens.', false,
    'DELETE FROM msz_users_password_resets WHERE reset_requested < NOW() - INTERVAL 1 WEEK');

msz_sched_task_sql('Remove old login attempt logs.', false,
    'DELETE FROM msz_login_attempts WHERE attempt_created < NOW() - INTERVAL 1 MONTH');

msz_sched_task_sql('Remove old audit log entries.', false,
    'DELETE FROM msz_audit_log WHERE log_created < NOW() - INTERVAL 3 MONTH');

msz_sched_task_sql('Remove stale forum tracking entries.', false,
    'DELETE tt FROM msz_forum_topics_track AS tt LEFT JOIN msz_forum_topics AS t ON t.topic_id = tt.topic_id WHERE t.topic_bumped < NOW() - INTERVAL 1 MONTH');

msz_sched_task_sql('Synchronise forum_id.', true,
    'UPDATE msz_forum_posts AS p INNER JOIN msz_forum_topics AS t ON t.topic_id = p.topic_id SET p.forum_id = t.forum_id');

msz_sched_task_func('Recount forum topics and posts.', true,
    function() { forum_count_synchronise(); });

msz_sched_task_sql('Clean up expired 2fa tokens.', false,
    'DELETE FROM msz_auth_tfa WHERE tfa_created < NOW() - INTERVAL 15 MINUTE');

echo 'Running ' . count($schedTasks) . ' tasks...' . PHP_EOL;

$dbConn = $msz->getDbConn();

foreach($schedTasks as $task) {
    echo '=> ' . $task->name . PHP_EOL;
    $success = true;

    try {
        switch($task->type) {
            case 'sql':
                $affected = $dbConn->execute($task->command);
                echo $affected . ' rows affected. ' . PHP_EOL;
                break;

            case 'func':
                $result = ($task->command)();
                if(is_bool($result))
                    $success = $result;
                break;

            default:
                $success = false;
                echo 'Unknown task type.' . PHP_EOL;
                break;
        }
    } catch(Exception $ex) {
        $success = false;
        echo (string)$ex;
    } finally {
        if($success)
            echo 'Done!';
        else
            echo '!!! FAILED !!!';
        echo PHP_EOL;
    }

    echo PHP_EOL;
}

echo 'Took ' . number_format(microtime(true) - MSZ_STARTUP, 5) . 'ms.' . PHP_EOL;
