<?php

header('Access-Control-Allow-Origin: *');

if ($_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'HEAD') {
    header('Content-Type: application/json; charset=UTF-8');
    header('Status: 405');
    header('Content-Length: 56');
    header('Allow: GET, HEAD');
    echo "{\"error\":\"method not allowed\",\"allow\":[\"GET\",\"HEAD\"]}\n";
    exit;
}

$info = $_SERVER['PATH_INFO'];
if ($info === '') {
    header('Content-Type: application/json; charset=UTF-8');
    header('Status: 404');
    header('Content-Length: 22');
    echo "{\"error\":\"not found\"}\n";
    exit;
}
$certId = substr($info, 1);

$file = tmpfile();
if (!$file) {
    header('Content-Type: application/json; charset=UTF-8');
    header('Status: 500');
    header('Content-Length: 34');
    echo "{\"error\":\"internal server error\"}\n";
    exit;
}
$filename = stream_get_meta_data($file)['uri'];
if (($pdfName = exec("python3 .attachment.py " . escapeshellarg($certId) . " 2>&1 > $filename ")) === "404") {
    header('Content-Type: application/json; charset=UTF-8');
    header('Status: 404');
    header('Content-Length: 22');
    echo "{\"error\":\"not found\"}\n";
    exit;
}

header('Content-Type: application/pdf');
header('Content-Length: ' . filesize($filename));
header('Content-Disposition: inline; filename="' . $pdfName . '"');
readfile($filename);
