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

with lib;

let
  cfg = config.mossnet.gonic;
  configFile = "/etc/gonic/config";
  dataFolder = "/var/lib/gonic";
in {
  options = {

    mossnet.gonic = {
      enable = mkEnableOption "Gonic music server and streamer";

      settings = lib.mkOption {
        type = types.str;
        default = {};
        example = literalExample ''
            music-path        <path to your music dir>
            podcast-path      <path to your podcasts dir>
            cache-path        <path to cache dir>
        '';
        description = ''
          Configuration for Gonic, see <link xlink:href="https://github.com/sentriz/gonic"/> for supported values.
      '';
      };

      user = mkOption {
        type = types.str;
        default = "gonic";
        description = "User account under which gonic runs.";
      };

      group = mkOption {
        type = types.str;
        default = "gonic";
        description = "Group account under which gonic runs.";
      };

    };
  };

  config = mkIf cfg.enable {

    environment.etc."gonic/config".text = cfg.settings;

    systemd.services.gonic = {
      description = "gonic Music Server and Streamer compatible with Subsonic/Airsonic";
      after = [ "remote-fs.target" "network.target" ];
      wantedBy = [ "multi-user.target" ];
      environment = {
        #GONIC_MUSIC_PATH
        #GONIC_PODCAST_PATH
        #GONIC_CACHE_PATH
        #GONIC_DB_PATH
        GONIC_SCAN_INTERVAL="800";
        #...
      };
      serviceConfig = {
        ExecStart = "${pkgs.gonic}/bin/gonic -config-path /etc/gonic/config";
        WorkingDirectory = dataFolder;
        TimeoutStopSec = "20";
        KillMode = "process";
        Restart = "on-failure";
        RestartSec = "10";
        User = cfg.user;
        Group = cfg.group;
        DevicePolicy = "closed";
        NoNewPrivileges= " yes";
        PrivateTmp = "yes";
        PrivateUsers = "yes";
        ProtectControlGroups = "yes";
        ProtectKernelModules = "yes";
        ProtectKernelTunables = "yes";
        RestrictAddressFamilies = "AF_UNIX AF_INET AF_INET6";
        RestrictNamespaces = "yes";
        RestrictRealtime = "yes";
        SystemCallFilter = "~@clock @debug @module @mount @obsolete @privileged @reboot @setuid @swap";
        ReadWritePaths = dataFolder;
        StateDirectory = baseNameOf dataFolder;
      };
    };

    users.users = optionalAttrs (cfg.user == "gonic") ({
      gonic = {
        description = "gonic service user";
        name = cfg.user;
        group = cfg.group;
        isSystemUser = true;
      };
    });

    users.groups = optionalAttrs (cfg.group == "gonic") ({
      gonic = {};
    });
    
    services.nginx.virtualHosts."music.mossnet.lan" = {
      enableACME = false;
      forceSSL = false;

      locations."/" = {
        extraConfig = ''
          proxy_pass http://localhost:4747/;
          proxy_set_header X-Forwarded-Host $host;
        '';
      };
    };
  };
}
