false, 'error' => 'Cannot detect local host']); exit; } $hostUpper = strtoupper($host); $varName = $hostUpper . '_UNRAID_API_KEY'; $confFile = $host . '.conf'; // Create/overwrite the Varaverk API key. // --description and --roles are required to suppress interactive prompts. // --overwrite replaces any existing key with the same name (keeps it to one). $dbg = ['ts' => date('H:i:s'), 'user' => trim(shell_exec('whoami'))]; $output = shell_exec('timeout 10 /usr/local/sbin/unraid-api apikey --name "Varaverk" --create --overwrite --description "Varaverk plugin" --roles ADMIN --json &1'); $dbg['raw'] = $output; file_put_contents('/tmp/vv_apikey_debug.json', json_encode($dbg, JSON_PRETTY_PRINT)); if (!$output) { echo json_encode(['ok' => false, 'error' => 'unraid-api returned no output — check /tmp/vv_apikey_debug.json']); exit; } $data = json_decode(trim($output), true); if (!is_array($data)) { echo json_encode(['ok' => false, 'error' => 'Could not parse unraid-api output', 'raw' => substr($output, 0, 300)]); exit; } $key = $data['key'] ?? null; if (!$key) { echo json_encode(['ok' => false, 'error' => 'No key in response', 'raw' => substr($output, 0, 300)]); exit; } // Read conf, replace the key value, write back $raw = vv_read_conf_raw($confFile); if ($raw === '') { echo json_encode(['ok' => false, 'error' => 'Cannot read ' . $confFile]); exit; } // If line is missing (older conf created before this field was added to the template), // insert it after HOST*_OWNER_EMAIL, or after HOST*_SSH_KEY, or append to file. if (!str_contains($raw, $varName)) { $inserted = false; foreach ([$hostUpper . '_OWNER_EMAIL', $hostUpper . '_SSH_KEY'] as $anchor) { if (str_contains($raw, $anchor)) { $raw = preg_replace( '/^(\s*' . preg_quote($anchor, '/') . '\s*=.*$)/m', '$1' . "\n " . $varName . '=""', $raw, 1 ); $inserted = true; break; } } if (!$inserted) { $raw = rtrim($raw) . "\n " . $varName . '=""' . "\n"; } } // Replace quoted value in-place $updated = preg_replace( '/^(\s*' . preg_quote($varName, '/') . '\s*=\s*)"[^"]*"/m', '${1}"' . $key . '"', $raw ); if (!vv_write_conf_raw($confFile, $updated)) { echo json_encode(['ok' => false, 'error' => 'Failed to write ' . $confFile]); exit; } echo json_encode([ 'ok' => true, 'key_preview' => substr($key, 0, 8) . '...' . substr($key, -4), 'conf_file' => $confFile, ]);