<?php
// Minimal Hasbak Gateway: GET /prices
// Auth: HMAC SHA256 of "{ts}:{path}" with shared secret
// Headers: X-TS, X-SIGN

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

function deny($code, $msg) {
  http_response_code($code);
  echo json_encode(['ok'=>false,'error'=>$msg], JSON_UNESCAPED_UNICODE);
  exit;
}

$envFile = '/etc/hasbak-gateway.env';
if (!is_readable($envFile)) deny(500, 'Env file missing');

$env = file_get_contents($envFile);
preg_match('/HASBAK_HMAC_SECRET=(.*)/', $env, $m);
$secret = isset($m[1]) ? trim($m[1]) : '';
if ($secret === '') deny(500, 'Secret missing');

$ts   = $_SERVER['HTTP_X_TS']   ?? '';
$sign = $_SERVER['HTTP_X_SIGN'] ?? '';
if ($ts === '' || $sign === '') deny(401, 'Missing auth headers');

if (!ctype_digit((string)$ts)) deny(401, 'Invalid TS');

$tsInt = (int)$ts;
// 30 saniye tolerans (istersen 60 yaparız)
if (abs(time() - $tsInt) > 30) deny(401, 'TS expired');

$path = '/prices';
$expected = hash_hmac('sha256', $tsInt . ':' . $path, $secret);

// constant-time compare
if (!hash_equals($expected, $sign)) deny(401, 'Bad signature');

// Redis'ten oku (php-redis varsa)
$key = 'prices:has';
$value = null;

if (class_exists('Redis')) {
  try {
    $r = new Redis();
    $r->connect('127.0.0.1', 6379, 1.0);
    $value = $r->get($key);
  } catch (Throwable $e) {
    $value = null;
  }
}

if ($value === null || $value === false) {
  // fallback: redis-cli
  $out = @shell_exec("redis-cli GET " . escapeshellarg($key));
  $value = $out ? trim($out) : null;
}

if (!$value) deny(503, 'No price data');

// redis-cli çıktısı bazen quote ile gelir:  "{...}"
// temizle
$value = trim($value);
if (strlen($value) > 0 && $value[0] === '"' && substr($value, -1) === '"') {
  $value = stripcslashes(substr($value, 1, -1));
}

$data = json_decode($value, true);
if (!is_array($data)) deny(503, 'Bad price json');

echo json_encode(['ok'=>true,'data'=>$data], JSON_UNESCAPED_UNICODE);
