<?php
declare(strict_types=1);

header('Content-Type: application/json');

$cfg = require __DIR__ . '/../config.php';

$tenantsDir = rtrim((string)($cfg['tenants_dir'] ?? '/home/mytown/blog.mytown.ink/tenants'), '/');
$pkgPath    = (string)($cfg['app_package_path'] ?? '');
$pkgName    = (string)($cfg['app_package_filename'] ?? 'blogger-app-package.tar.gz');
$logFile    = (string)($cfg['kit_package_log'] ?? ($tenantsDir . '/_kit_package.log'));

function logpkg(string $msg): void {
  global $logFile;
  @file_put_contents($logFile, '[' . date('c') . '] ' . $msg . PHP_EOL, FILE_APPEND);
}

function env_get(string $envPath, string $key): string {
  if (!is_file($envPath)) return '';
  $env = file_get_contents($envPath) ?: '';
  if (preg_match('/^' . preg_quote($key, '/') . '=(.*)$/m', $env, $m)) {
    return trim($m[1]);
  }
  return '';
}

$raw = file_get_contents('php://input') ?: '';
$body = json_decode($raw, true);

if (!is_array($body)) {
  http_response_code(400);
  echo json_encode(['ok' => false, 'error' => 'Invalid JSON']);
  exit;
}

$ref = trim((string)($body['ref'] ?? ''));
$license = trim((string)($body['license'] ?? ''));

if (!preg_match('/^t_[a-f0-9]{16}$/', $ref)) {
  http_response_code(400);
  echo json_encode(['ok' => false, 'error' => 'Invalid ref']);
  exit;
}

if ($license === '' || strlen($license) < 8) {
  http_response_code(400);
  echo json_encode(['ok' => false, 'error' => 'Invalid license']);
  exit;
}

$tenantDir  = $tenantsDir . '/' . $ref;
$activePath = $tenantDir . '/active.json';
$envPath    = $tenantDir . '/.env';

if (!is_dir($tenantDir) || !is_file($activePath) || !is_file($envPath)) {
  http_response_code(404);
  echo json_encode(['ok' => false, 'error' => 'Tenant not found']);
  exit;
}

$active = json_decode((string)file_get_contents($activePath), true);
if (!is_array($active) || strtolower((string)($active['status'] ?? '')) !== 'active') {
  http_response_code(403);
  echo json_encode(['ok' => false, 'error' => 'Tenant not active']);
  exit;
}

$storedLicense = env_get($envPath, 'LICENSE_KEY');
if ($storedLicense === '' || !hash_equals($storedLicense, $license)) {
  logpkg('DENY ref=' . $ref . ' reason=bad_license ip=' . ($_SERVER['REMOTE_ADDR'] ?? ''));
  http_response_code(403);
  echo json_encode(['ok' => false, 'error' => 'License mismatch']);
  exit;
}

if ($pkgPath === '' || !is_file($pkgPath) || filesize($pkgPath) < 1024) {
  http_response_code(500);
  echo json_encode(['ok' => false, 'error' => 'Package missing on server']);
  exit;
}

logpkg('SERVE ref=' . $ref . ' ip=' . ($_SERVER['REMOTE_ADDR'] ?? '') . ' ua=' . ($_SERVER['HTTP_USER_AGENT'] ?? ''));

// Stream the package
header_remove('Content-Type');
header('Content-Type: application/gzip');
header('Content-Disposition: attachment; filename="' . $pkgName . '"');
header('Content-Length: ' . filesize($pkgPath));
header('X-Content-Type-Options: nosniff');

$fp = fopen($pkgPath, 'rb');
if (!$fp) {
  http_response_code(500);
  echo json_encode(['ok' => false, 'error' => 'Cannot read package']);
  exit;
}

fpassthru($fp);
fclose($fp);
exit;
