{ config, lib, pkgs, ... }:

let

  owncastArchiver = with pkgs; writeScript "owncast-archiver.sh" ''
    #! ${runtimeShell} -e

    PATH=${lib.makeBinPath [ coreutils curl jq ffmpeg ]}

    while true; do

      STATUS="$(curl -s https://owncast.c3d2.de/api/status)"
      ONLINE="$(echo "$STATUS" | jq -r .online)"
      if [ "$ONLINE" = true ]; then
        TITLE="$(echo "$STATUS" | jq -r .streamTitle)"
        ffmpeg -i https://owncast.c3d2.de/hls/0/stream.m3u8 -c copy "$(echo "$(date -Iseconds)_$TITLE.mkv"|tr " +<>:/" "____\\-\\-")"
      fi

      sleep ${toString cfg.pollInterval}
    done
  '';

  cfg = config.services.owncast-archiver;

in

{
  options.services.owncast-archiver = with lib; {
    enable = mkEnableOption "owncast archiver";

    targetDir = mkOption {
      type = types.str;
      default = "/mnt/archive";
    };

    pollInterval = mkOption {
      type = types.int;
      default = 10;
    };
  };

  config = lib.mkIf cfg.enable {
    users.users.archiver = {
      isSystemUser = true;
      group = "nginx";
    };

    systemd.services.owncast-archiver = {
      wantedBy = [ "multi-user.target" ];
      after = [ "owncast.service" ];
      serviceConfig = {
        ReadWritePaths = cfg.targetDir;
        WorkingDirectory = cfg.targetDir;
        User = "archiver";
        ExecStart = owncastArchiver;
        Restart = "always";
        RestartSec = 60;
      };
    };
  };
}
