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

function http_get_json($url) {
  if (function_exists('curl_init')) {
    $ch = curl_init($url);
    curl_setopt_array($ch, array(
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_CONNECTTIMEOUT => 8,
      CURLOPT_TIMEOUT => 18,
      CURLOPT_HTTPHEADER => array('Accept: application/json', 'User-Agent: L2MetaCDNSync/1.0'),
      CURLOPT_FOLLOWLOCATION => true,
    ));
    $raw = curl_exec($ch);
    $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $err = curl_error($ch);
    curl_close($ch);
    if ($raw === false || $code < 200 || $code >= 300) {
      return array(null, $err !== '' ? $err : ('HTTP ' . $code));
    }
    return array($raw, null);
  }
  $ctx = stream_context_create(array(
    'http' => array(
      'timeout' => 18,
      'header' => "Accept: application/json\r\nUser-Agent: L2MetaCDNSync/1.0\r\n",
    ),
  ));
  $raw = @file_get_contents($url, false, $ctx);
  if ($raw === false) {
    return array(null, 'file_get_contents failed');
  }
  return array($raw, null);
}

$dir = __DIR__;
$metaFile = $dir . '/site-feeds-meta.json';
$ttl = 3600;
$now = time();
$meta = array('synced_at_unix' => 0);
if (is_file($metaFile)) {
  $decoded = json_decode(@file_get_contents($metaFile), true);
  if (is_array($decoded)) {
    $meta = $decoded;
  }
}
$age = $now - (int)(isset($meta['synced_at_unix']) ? $meta['synced_at_unix'] : 0);
if ($age >= 0 && $age < $ttl && !empty($meta['synced_at_unix'])) {
  http_response_code(204);
  echo json_encode(array('ok' => true, 'skipped' => true, 'age' => $age, 'ttl' => $ttl));
  exit;
}

$lockPath = $dir . '/site-feeds-sync.lock';
$lock = @fopen($lockPath, 'c+');
if ($lock === false || !@flock($lock, LOCK_EX | LOCK_NB)) {
  http_response_code(204);
  echo json_encode(array('ok' => true, 'skipped' => true, 'busy' => true));
  exit;
}

$origin = 'https://l2meta.net';
$by = array();
foreach (array('ru', 'en', 'uk') as $loc) {
  list($raw, $err) = http_get_json($origin . '/' . $loc . '/api/home-hero-servers');
  if ($raw === null) {
    @flock($lock, LOCK_UN);
    @fclose($lock);
    http_response_code(502);
    echo json_encode(array('ok' => false, 'error' => 'home-hero ' . $loc, 'detail' => $err));
    exit;
  }
  $by[$loc] = json_decode($raw, true);
}

if (@file_put_contents($dir . '/home-hero-servers.json', json_encode($by, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)) === false) {
  @flock($lock, LOCK_UN);
  @fclose($lock);
  http_response_code(500);
  echo json_encode(array('ok' => false, 'error' => 'write home-hero-servers.json'));
  exit;
}

list($streamsRaw, $err) = http_get_json($origin . '/api/launcher-streams');
if ($streamsRaw === null) {
  @flock($lock, LOCK_UN);
  @fclose($lock);
  http_response_code(502);
  echo json_encode(array('ok' => false, 'error' => 'launcher-streams', 'detail' => $err));
  exit;
}
if (@file_put_contents($dir . '/launcher-streams.json', $streamsRaw) === false) {
  @flock($lock, LOCK_UN);
  @fclose($lock);
  http_response_code(500);
  echo json_encode(array('ok' => false, 'error' => 'write launcher-streams.json'));
  exit;
}

$meta = array('synced_at_unix' => $now, 'synced_at' => gmdate('c'));
@file_put_contents($metaFile, json_encode($meta));
@flock($lock, LOCK_UN);
@fclose($lock);
echo json_encode(array('ok' => true, 'synced_at_unix' => $now));
