#!/usr/bin/env php
<?php


declare(strict_types=1);
if (php_sapi_name() !== 'cli') { echo "CLI only\n"; exit(1); }
require dirname(__DIR__) . '/config/php-guard.php';  
require dirname(__DIR__) . '/config/app.php';
try { Database::reconnect(); } catch (\Throwable $e) {}

$pidFile = APP_ROOT . '/storage/tmp/heartbeat.pid';
if (!is_dir(dirname($pidFile))) @mkdir(dirname($pidFile), 0755, true);
file_put_contents($pidFile, (string) getmypid());

$url = '';
try { $url = rtrim(Setting::get('site_url', ''), '/') . '/'; } catch (\Throwable $e) {}

while (true) {
    sleep(50);
    try {
         
        try {
            if (Setting::get('heartbeat_enabled', '1') !== '1') break;
            $u = rtrim(Setting::get('site_url', ''), '/') . '/';
            if ($u !== '/') $url = $u;
        } catch (\Throwable $e) { try { Database::reconnect(); } catch (\Throwable $e2) {} }

        if ($url === '' || $url === '/') continue;
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER    => true,
            CURLOPT_TIMEOUT           => 15,
            CURLOPT_CONNECTTIMEOUT    => 5,
            CURLOPT_NOBODY            => true,
            CURLOPT_SSL_VERIFYPEER    => true,
            CURLOPT_USERAGENT         => 'TubePress-Heartbeat/1.0',
        ]);
        @curl_exec($ch);
        curl_close($ch);
    } catch (\Throwable $e) {
        error_log('heartbeat: ' . $e->getMessage());
    }
}
@unlink($pidFile);
