libnss: better handling of env vars

This commit is contained in:
Motiejus Jakštys 2022-07-06 14:06:50 +03:00
parent 59eae5fa3b
commit 64f6af6e94

View File

@ -19,7 +19,7 @@ const c = @cImport({
});
const ENV_DB = "TURBONSS_DB";
const ENV_VERBOSE = "TURBONSS_VERBOSE";
const ENV_LOGLEVEL = "TURBONSS_LOGLEVEL";
const ENV_OMIT_MEMBERS = "TURBONSS_OMIT_MEMBERS";
export var turbonss_db_path: [:0]const u8 = "/etc/turbonss/db.turbo";
@ -41,18 +41,47 @@ var global_init = once(init);
// assigns State from environment variables et al
fn init() void {
if (os.getenvZ(ENV_VERBOSE)) |env|
log_level = if (mem.eql(u8, mem.sliceTo(env, 0), "1"))
.debug
else
.err;
if (os.getenvZ(ENV_LOGLEVEL)) |env| {
const got = mem.sliceTo(env, 0);
if (mem.eql(u8, got, "0")) {
log_level = .err;
} else if (mem.eql(u8, got, "1")) {
log_level = .warn;
} else if (mem.eql(u8, got, "2")) {
log_level = .info;
} else if (mem.eql(u8, got, "3")) {
log_level = .debug;
} else {
std.debug.print(
"warning: unrecognized {s}={s}. Expected between 0 and 3\n",
.{ ENV_LOGLEVEL, got },
);
}
}
const omit_members = blk: {
if (os.getenvZ(ENV_OMIT_MEMBERS)) |env| {
const got = mem.sliceTo(env, 0);
if (mem.eql(u8, got, "1")) {
break :blk true;
} else if (mem.eql(u8, got, "0")) {
break :blk false;
} else if (mem.eql(u8, got, "auto")) {
// not set, do autodiscover
} else {
std.debug.print(
"warning: unrecognized {s}={s}. Expected 0, 1 or auto\n",
.{ ENV_OMIT_MEMBERS, got },
);
}
}
if (os.argv.len == 0) break :blk false;
break :blk mem.eql(u8, mem.sliceTo(os.argv[0], 0), "id");
};
log.debug("omitting members from getgr* calls: {any}\n", .{omit_members});
const fname = os.getenvZ(ENV_DB) orelse turbonss_db_path[0..];
log.debug("opening {s}", .{fname});
const env_omit_members = os.getenvZ(ENV_OMIT_MEMBERS) orelse "auto";
const omit_members = shouldOmitMembers(env_omit_members, os.argv);
log.debug("omitting members from getgr* calls: {any}\n", .{omit_members});
log.debug("opening '{s}'", .{fname});
const file = File.open(fname) catch |err| {
log.warn("open '{s}': {s}", .{ fname, @errorName(err) });