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

with lib;

let
  sheepdog = pkgs.sheepdog;
  cfg = config.services.sheepdog;
  stateDir = "/var/lib/sheepdog";
  pidFile = "${stateDir}/run/sheep.pid";
in
{
  ###### interface

  options = {
    services.sheepdog = {
      enable = mkEnableOption "Sheepdog Daemon";

      config = mkOption {
        type = types.lines;
        default = "--cluster local --log dst=syslog --upgrade";
        description = ''
          Configuration directives that should be added to
          <literal>sheep commandline</literal>.
        '';
      };

      pidFile = mkOption {
        type = types.string;
        default = "${pidFile}";
        description = ''
          Where to write the pidfile
        '';
      };

      stateDir = mkOption {
        type = types.string;
        default = "${stateDir}";
        description = ''
          Where to store the cluster metadata and objects
        '';
      };
    };
  };

  ###### implementation

  config = mkIf config.services.sheepdog.enable {
    users.extraUsers = singleton {
      name = "sheepdog";
      uid = config.ids.uids.sheepdog;
      description = "Sheepdog daemon user";
    };

    users.extraGroups = singleton {
      name = "sheepdog";
      gid = config.ids.gids.sheepdog;
    };

    systemd.services.sheepdog = {
      description = "Sheepdog daemon";
      after = [ "network.target" "systemd-resolved.service" ];
      wants = [ "syslog.target" ];
      wantedBy = [ "multi-user.target" ];
      path = [ sheepdog ];
      preStart = ''
        if [ ! -d ${cfg.stateDir} ]; then
          mkdir -m 755 -p ${cfg.stateDir}
          chown -R sheepdog:sheepdog ${cfg.stateDir}
        fi

        pidFileDir=$(dirname ${cfg.pidFile})
        if [ ! -d ''${pidFileDir} ]; then
          mkdir -m 755 -p ''${pidFileDir}
          chown -R sheepdog:sheepdog ''${pidFileDir}
        fi
      '';

      serviceConfig = {
        Type = "forking";
        ExecStart = "${sheepdog}/bin/sheep --pidfile ${cfg.pidFile} ${cfg.config} ${cfg.stateDir}";
        PIDFile = "${stateDir}/run/sheep.pid";
        PermissionsStartOnly = true;
        User = "sheepdog";
        Group = "sheepdog";
      };
    };
  };
}