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

let
  cfg = config.services.henna;
in
{
  options.services.henna = {
    enable = lib.mkEnableOption "Henna gallery server";

    package = lib.mkOption {
      type = lib.types.package;
      default = pkgs.callPackage ./default.nix { };
      description = "The henna package to use.";
    };

    imaginaryUrl = lib.mkOption {
      type = lib.types.str;
      description = "Imaginary server root URL.";
    };

    galleryPath = lib.mkOption {
      type = lib.types.path;
      description = "Path to the gallery directory.";
    };

    databasePath = lib.mkOption {
      type = lib.types.path;
      default = ./db.sqlite;
      description = "Path to the SQLite database file.";
    };

    address = lib.mkOption {
      type = lib.types.str;
      default = "localhost";
      description = "Address to listen on.";
    };

    port = lib.mkOption {
      type = lib.types.port;
      default = 10000;
      description = "Port to listen on.";
    };

    user = lib.mkOption {
      type = lib.types.str;
      default = "henna";
      description = "User to run henna as.";
    };

    group = lib.mkOption {
      type = lib.types.str;
      default = "henna";
      description = "Group to run henna as.";
    };
  };

  config = lib.mkIf cfg.enable {
    users.users.${cfg.user} = {
      isSystemUser = true;
      group = cfg.group;
    };

    users.groups.${cfg.group} = { };

    systemd.services.henna = {
      description = "Henna gallery server";
      wantedBy = [ "multi-user.target" ];
      after = [ "network.target" ];

      serviceConfig = {
        ExecStart = ''
          ${cfg.package}/bin/henna \
            -imaginary "${cfg.imaginaryUrl}" \
            -gallery "${cfg.galleryPath}" \
            -database "${cfg.databasePath}" \
            -address "${cfg.address}" \
            -port ${toString cfg.port}
        '';
        User = cfg.user;
        Group = cfg.group;
        Restart = "on-failure";
        RestartSec = 5;
      };
    };
  };
}
