<?php
require_once dirname(__DIR__) . '/lib/boardroom-auth.php';
require_once __DIR__ . '/fl-path.php';
require_once __DIR__ . '/fl-meta.php';

boardroom_session_start();

header('Content-Type: text/plain; charset=UTF-8');

$path = isset($_POST['path']) ? (string) $_POST['path'] : '';
$field = isset($_POST['field']) ? (string) $_POST['field'] : 'APP_DESCRIPTION';
$value = isset($_POST['value']) ? (string) $_POST['value'] : (isset($_POST['description']) ? (string) $_POST['description'] : '');

$base = realpath(__DIR__);
if ($base === false) {
    echo 'NG:base';
    exit;
}

$rel = boardroom_norm_rel($path);
if (!boardroom_can_access('data' . ($rel !== '' ? '/' . $rel : ''))) {
    echo 'NG:auth';
    exit;
}

$full = fl_resolve_path($path, $base);

if (!$full || !is_file($full)) {
    echo 'NG:path';
    exit;
}

$field = fl_meta_normalize_field($field);

if ($field === '') {
    echo 'NG:field';
    exit;
}

if (!fl_write_meta($full, $field, $value)) {
    echo 'NG:write';
    exit;
}

echo 'OK';
exit;
