{ 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" {};
    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";
        };
      };

      secretsFile = mkOption {
        type = types.path;
        description = mdDoc "Path to secrets file that defines MATRIX_ACCESS_TOKEN";
      };

    };
  };

  config = mkIf cfg.enable {
    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@
       '';
      in ''
        ${pkgs.replace-secret}/bin/replace-secret '@MATRIX_ACCESS_TOKEN@' ${cfg.settings.secretsFile} /run/pvv-calendar-bot/env
      '';

      serviceConfig = {
        ExecStart = "${cfg.package}/bin/pvv-calendar-bot";
        RuntimeDirectory = "pvv-calendar-bot";
        DynamicUser = true;
        EnvironmentFile = [ "-/run/pvv-calendar-bot/env" ];
      };
    };

  };

}