{ config, containerCfg, pkgs, lib, builder, name,... }:
let 
  serverCfg = config.syscfg.server;
  version = "5.1.4"; 

in {
  runtime = {
    paths = [
      { path="${serverCfg.path.config.path}/openhab/conf";  owner="1000:1000"; mode = "0755"; }
      { path="${serverCfg.path.config.path}/openhab/userdata";  owner="1000:1000"; mode = "0755"; }
      { path="${serverCfg.path.config.path}/openhab/addons";  owner="1000:1000"; mode = "0755"; }
    ];

    containers = {
      server = builder.mkContainer {
        subdomain = containerCfg.subdomain;
        image = "openhab/openhab:${version}";
        port = 8080; 
        extraEnv = { 
          USER_ID = "1000";
          GROUP_ID = "1000";
          CRYPTO_POLICY = "unlimited";
          OPENHAB_HTTP_PORT = "8080";
        };
        extraOptions = [
          "--network=host"
          "--cap-add=NET_ADMIN"
          "--cap-add=NET_RAW"
          "--no-healthcheck"
        ];
        overrides = {
          volumes = [ 
            "${serverCfg.path.config.path}/openhab/conf:/openhab/conf"
            "${serverCfg.path.config.path}/openhab/userdata:/openhab/userdata"
            "${serverCfg.path.config.path}/openhab/addons:/opt/openhab/addons"
            "/var/run/dbus/system_bus_socket:/var/run/dbus/system_bus_socket:ro"
          ];
         };
      };
    };

    setup = {
      trigger = "server";
      envFile = [ config.sops.secrets."CUSTOM".path ];
      script = pkgs.writeShellScript "setup" ''
        # Pre-generate openHAB directories on the host
        OHAB="${pkgs.podman}/bin/podman --events-backend=none exec openhab-server /openhab/runtime/bin/client -u openhab -p habopen"
        sleep 20
        exit 0
        $OHAB openhab:users add $DEFAULT_ADMIN_USERNAME $DEFAULT_ADMIN_PASSWORD administrator 
        $OHAB feature:list
        $OHAB openhab:addons install persistance-mapdb
        $OHAB openhab:addons install persistance-influxdb

        $OHAB openhab:addons install ui-basic
        $OHAB openhab:addons install automation-jsscripting

        $OHAB openhab:addons install binding-telegram
        $OHAB openhab:addons install binding-matter
        $OHAB openhab:addons install binding-mqtt
        $OHAB openhab:addons install binding-bluetooth
        $OHAB openhab:addons install binding-zigbee
        $OHAB openhab:addons install binding-chromecast
        $OHAB openhab:addons install binding-astro
        $OHAB openhab:addons install binding-meteoblue
        $OHAB openhab:addons install binding-publictransportswitzerland

        #IF APPLE DEVICE: HomeKit (siri/apple bridge)
        #IF UBIQUITY NET: Unifi + UnifiProtect (net/cam bridge)
        #IF YAMAHA+EPSON: EpsonProjector + Yamaha (projector and sound)
        #IF BAMBULAB DEVICE: BambuLab (notify print state)
        #IF GARDENA DEVICE: Gardena (smart watering)
        #Extra: AndroidTV/Jellyfin (Bind with lights + more)
      '';
    };
  };
}
