<?php

declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');

// SHA-256 of the configured bearer token. Keep the plaintext token only on
// the client that performs the scheduled request.
const TOKEN_SHA256 = '0554291eb5b3703815bfe01b7a2c9bb61da20c3267d73e37e900380c14eec93e';
const IP_FILE = __DIR__ . '/ip.txt';

function respond(int $status, array $body): never
{
    http_response_code($status);
    echo json_encode($body, JSON_UNESCAPED_SLASHES) . "\n";
    exit;
}

$token = $_GET['token'] ?? '';
if (!is_string($token) || !hash_equals(TOKEN_SHA256, hash('sha256', $token))) {
    respond(401, ['ok' => false, 'error' => 'unauthorized']);
}

$ip = $_SERVER['REMOTE_ADDR'] ?? '';
if (!is_string($ip) || filter_var($ip, FILTER_VALIDATE_IP) === false) {
    respond(400, ['ok' => false, 'error' => 'invalid client IP']);
}

if (file_put_contents(IP_FILE, $ip . "\n", LOCK_EX) === false) {
    respond(500, ['ok' => false, 'error' => 'cannot write ip.txt']);
}

respond(200, ['ok' => true, 'ip' => $ip]);
