{ config, lib, pkgs, ... }:
with lib;
with types;
let
  cfg = config.custom.services.castget;
in
{

  options.custom.services.castget = {
    enable = mkEnableOption "enable custom.services.castget";
    feeds = mkOption {
      type = attrsOf (submodule {
        options = {
          url = mkOption {
            type = str;
            description = ''
              url to the rss feed
            '';
          };
          spool = mkOption {
            type = path;
            description = ''
              download enclosures to this directory.
            '';
          };
        };
      });
      description = ''
        configurations for the cast
      '';
    };
    user = mkOption {
      type = str;
      description = ''
        user to run the systemd service as
      '';
    };
    timerConfig = mkOption {
      type = attrsOf str;
      default = { OnCalendar = "daily"; };
      example = {
        OnCalendar = "00:05";
        RandomizedDelaySec = "5h";
      };
      description = ''
        When to run the polling script. See man systemd.timer for details.
      '';
    };
    serviceName = mkOption {
      type = str;
      default = "castget";
      description = ''
        the name of the castget systemd service
      '';
    };
  };

  config = mkIf cfg.enable {

    systemd.services."${cfg.serviceName}" = {
      description = "castget polling service";
      after = [ "network.target" ];
      wantedBy = [ "multi-user.target" ];
      restartIfChanged = false;
      serviceConfig.User = cfg.user;

      preStart =
        let
          mkSpools = mapAttrsToList (ignore: value: "mkdir -p \"${value.spool}\"") cfg.feeds;
        in
        concatStringsSep "\n" mkSpools;
      script =
        let
          channels = mapAttrsToList (key: ignore: key) cfg.feeds;
          castget = "${pkgs.castget}/bin/castget";

          configurationFile =
            let
              configurations = mapAttrsToList
                (key: value: ''
                  [${key}]
                  url=${value.url}
                  spool=${value.spool}
                '')
                cfg.feeds;
            in
            (pkgs.writeText "castget-configuration"
              (concatStringsSep "" configurations));
        in
        (concatMapStringsSep "\n"
          (channel: "${castget} --rcfile ${configurationFile} ${channel}")
          channels);
    };

    systemd.timers."${cfg.serviceName}" = {
      wantedBy = [ "timers.target" ];
      timerConfig = cfg.timerConfig;
    };

  };
}