{ config, lib, pkgs, ... }:
let
  cfg = config.services.plume;
in
{
  options.services.plume = with lib; {
    enable = mkEnableOption "Plume";

    envFile = mkOption {
      type = types.path;
      description = "Path to .env file";
    };

    user = mkOption {
      type = types.str;
      default = "plume";
      description = "System user to run Plume";
    };

    group = mkOption {
      type = types.str;
      default = "plume";
      description = "System group to run Plume";
    };
  };

  config = lib.mkIf cfg.enable {
    systemd.tmpfiles.rules = [
      "d ${config.users.users.${cfg.user}.home} 0700 ${cfg.user} ${cfg.group} -"
    ];

    ids.uids.plume = 499;
    users.users.${cfg.user} = {
      uid = config.ids.uids.plume;
      inherit (cfg) group;
      home = "/var/lib/plume";
    };
    users.groups.${cfg.group} = {};

    services.postgresql = {
      enable = true;
      initialScript = pkgs.writeText "plume-initScript" ''
        CREATE ROLE plume WITH LOGIN PASSWORD 'plume' CREATEDB;
        CREATE DATABASE plume;
        GRANT ALL PRIVILEGES ON DATABASE plume TO plume;
      '';
      # TODO: update to postgresql 15
    };

    systemd.services.plume = {
      description = "Plume";
      after = [ "postgresql.service" ];
      requires = [ "postgresql.service" ];
      wantedBy = [ "multi-user.target" ];
      path = [ pkgs.plume ];
      script = ''
        ln -sf ${cfg.envFile} .env
        mkdir -p static/media
        for f in ${pkgs.plume}/share/plume/static/*; do
          n=$(basename "$f")
          if [ "$n" != media ]; then
            rm -f "static/$n"
            ln -s "$f" "static/$n"
          fi
        done

        plm migration run
        plm search init
        exec plume
      '';
      serviceConfig = {
        User = cfg.user;
        Group = cfg.group;
        Restart = "on-failure";
        WorkingDirectory = config.users.users.${cfg.user}.home;
      };
    };

    environment.systemPackages = [ (pkgs.writeScriptBin "plume-setup" ''
      #! ${pkgs.runtimeShell} -e

      plm() {
        sudo -u ${config.services.plume.user} -- ${pkgs.plume}/bin/plm $@
      }

      plm migration run
      plm instance new
      plm users new --admin

      systemctl start plume.service
    '') ];
  };
}
