{ pkgs, lib, config, ... }:
let
  s3fs = { mount, bucket }: {
    age.secrets.jellyMount = {
      file = /etc/nixos/secrets/jellyMountPass.age;
      owner = "root";
      group = "root";
      mode = "0600";
    };
    
    systemd.services."s3fs-${bucket}" = {
      description = "Jellyfin Bucket Storage";
      wantedBy = [ "multi-user.target" ];

      serviceConfig = {
        ExecStartPre = [
          "${pkgs.coreutils}/bin/mkdir -m 0500 -pv ${mount}"
          "${pkgs.e2fsprogs}/bin/chattr +i ${mount}"  # Stop files being accidentally written to unmounted directory
        ];
        ExecStart = let
          options = [
            "passwd_file=${config.age.secrets.jellyMount.path}"
            "use_path_request_style"
            "allow_other"
            "url=http://localhost:7500"
            "umask=0077"
          ];
        in
          "${pkgs.s3fs}/bin/s3fs ${bucket} ${mount} -f "
          + lib.concatMapStringsSep " " (opt: "-o ${opt}") options;
        ExecStopPost = "-${pkgs.fuse}/bin/fusermount -u ${mount}";
        KillMode = "process";
        Restart = "on-failure";
      };
    };
  };
in
s3fs {
  mount = "/jelly";
  bucket = "jellyfin";
} 
