calendar-bot/module.nix

122 lines
3.6 KiB
Nix

{ config, lib, pkgs, ... }:
let
cfg = config.services.pvv-calendar-bot;
inherit (lib) mkDefault mkEnableOption mkPackageOption mkIf mkOption types mdDoc;
in
{
options.services.pvv-calendar-bot = {
enable = mkEnableOption (lib.mdDoc "Enable pvv-calendar-bot to post to matrix");
package = mkPackageOption pkgs "pvv-calendar-bot" { };
user = mkOption {
type = types.str;
default = "pvv-calendar-bot";
};
group = mkOption {
type = types.str;
default = "pvv-calendar-bot";
};
settings = {
onCalendar = mkOption {
type = types.str;
default = "9 0 * * *";
description = mdDoc "OnCalendar string for the systemd service(e.g. crontab format)";
};
matrix = {
user = mkOption {
type = types.str;
description = mdDoc "Matrix username to authenticate with";
example = "@bot_calendar:pvv.ntnu.no";
};
channel = mkOption {
type = types.str;
description = mdDoc "Room ID of the channel to post announcements in";
example = "!abcdef:matrix.org";
};
homeserver = mkOption {
type = types.str;
description = mdDoc "Matrix homeserver URL to connect to";
example = "https://matrix.org";
};
};
database = {
host = mkOption {
type = types.str;
description = mdDoc "MySQL host to connect to";
example = "mysql.pvv.ntnu.no";
};
user = mkOption {
type = types.str;
description = mdDoc "MySQL username to authenticate with";
example = "calendar-bot";
};
passwordFile = mkOption {
type = types.path;
description = mdDoc "Path to file containing MySQL password";
};
};
secretsFile = mkOption {
type = types.path;
description = mdDoc "Path to secrets file that defines MATRIX_ACCESS_TOKEN";
};
};
};
config = mkIf cfg.enable {
users.users = mkIf (cfg.user == "pvv-calendar-bot") {
pvv-calendar-bot = {
description = "PVV Calendar Matrix Bot User";
isSystemUser = true;
group = cfg.group;
};
};
users.groups = mkIf (cfg.group == "pvv-calendar-bot") {
pvv-calendar-bot = { };
};
systemd.timers."pvv-calendar-bot" = {
wantedBy = [ "timers.target" ];
timerConfig = {
OnCalendar = cfg.settings.onCalendar;
Unit = "pvv-calendar-bot";
};
};
systemd.services."pvv-calendar-bot" = {
preStart =
let
envFile = pkgs.writeText "pvv-calendar-bot-env" ''
MATRIX_URL=${cfg.settings.matrix.homeserver}
MATRIX_USER=${cfg.settings.matrix.user}
ANNOUNCEMENT_CHANNEL=${cfg.settings.matrix.channel}
MATRIX_TOKEN=@MATRIX_ACCESS_TOKEN@
MYSQL_HOST=${cfg.settings.database.host}
MYSQL_USER=${cfg.settings.database.user}
MYSQL_PASSWORD=@MYSQL_PASSWORD@
'';
in
''
install -Dm600 ${envFile} /run/pvv-calendar-bot/env
${pkgs.replace-secret}/bin/replace-secret '@MATRIX_ACCESS_TOKEN@' ${cfg.settings.secretsFile} /run/pvv-calendar-bot/env
${pkgs.replace-secret}/bin/replace-secret '@MYSQL_PASSWORD@' ${cfg.settings.database.passwordFile} /run/pvv-calendar-bot/env
'';
serviceConfig = {
ExecStart = "${cfg.package}/bin/pvv-calendar-bot";
RuntimeDirectory = "pvv-calendar-bot";
EnvironmentFile = [ "-/run/pvv-calendar-bot/env" ];
User = cfg.user;
Group = cfg.group;
};
};
};
}