42 lines
2.5 KiB
C#
42 lines
2.5 KiB
C#
using System.Text.Json;
|
|
|
|
namespace HealthApp.Provisioning;
|
|
|
|
public static class ConfigurationWriter
|
|
{
|
|
public static void Configure(string serviceDirectory, string root, string platform)
|
|
{
|
|
if (platform is not ("linux" or "windows" or "macos")) throw new InvalidOperationException("Unknown configuration platform.");
|
|
var service = Deployment.ReadService(serviceDirectory);
|
|
var directory = platform == "linux" ? Path.Combine(root, "etc", "healthapp", service.Name) : Path.Combine(root, "config", service.Name);
|
|
Directory.CreateDirectory(directory);
|
|
var destination = Path.Combine(directory, platform == "windows" ? "appsettings.Production.json" : "service.env");
|
|
if (File.Exists(destination)) throw new InvalidOperationException("Service configuration already exists; it was not overwritten.");
|
|
var env = new Dictionary<string, string>(service.Environment);
|
|
env["Kestrel__Certificates__Default__Path"] = Path.Combine(directory, "service.pfx");
|
|
if (service.Name == "api-gateway") env["Authentication__KeyDirectory"] = platform == "linux" ?
|
|
Path.Combine(root, "var", "lib", "healthapp-api-gateway", "keys") : Path.Combine(root, "state", "api-gateway", "keys");
|
|
File.Copy(Path.Combine(serviceDirectory, "service.pfx"), Path.Combine(directory, "service.pfx"));
|
|
if (platform == "windows")
|
|
{
|
|
var json = new Dictionary<string, object>();
|
|
foreach (var (key, value) in env)
|
|
{
|
|
if (key == "ASPNETCORE_ENVIRONMENT") continue; // Native service command line explicitly selects Production.
|
|
var parts = (key == "ASPNETCORE_URLS" ? "urls" : key).Split("__");
|
|
var current = json;
|
|
foreach (var part in parts[..^1])
|
|
{
|
|
if (!current.TryGetValue(part, out var child)) current[part] = child = new Dictionary<string, object>();
|
|
current = (Dictionary<string, object>)child;
|
|
}
|
|
current[parts[^1]] = value;
|
|
}
|
|
File.WriteAllText(destination, JsonSerializer.Serialize(json, Deployment.Json));
|
|
}
|
|
else File.WriteAllLines(destination, env.Select(p => p.Key + "=\"" + p.Value.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\""));
|
|
if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS())
|
|
foreach (var file in Directory.GetFiles(directory)) File.SetUnixFileMode(file, UnixFileMode.UserRead | UnixFileMode.UserWrite);
|
|
}
|
|
}
|