{ pkgs, ... }:
let
  hosts = import ../../hosts.nix;
in
{
  boot = {
    # kernelPackages = pkgs.linuxPackages_latest;
    kernelParams = [ "acpi_osi=Linux-Dell-Video" ];
    initrd.checkJournalingFS = true; # Use same ACPI identifier as Dell Ubuntu
    loader = {
      systemd-boot = { enable = true; editor = false; };
      efi.canTouchEfiVariables = true;
    };
  };

  console = { font = "Lat2-Terminus16"; keyMap = "it"; };

  i18n.defaultLocale = "it_IT.UTF-8";

  hardware = {
    enableAllFirmware = true;
    enableRedistributableFirmware = true;
    bluetooth = {
      enable = true;
      package = pkgs.bluez-experimental;
      # settings = {
      #   General = {
      #     ControllerMode = "bredr";
      #   };
      # };
    };
    cpu.intel.updateMicrocode = true;
    graphics = {
      enable = true;
      enable32Bit = true;
      extraPackages = [ pkgs.intel-media-driver ];
      extraPackages32 = [ pkgs.pkgsi686Linux.intel-media-driver ];
    };
    nvidia = {
      open = false;
      prime = {
        offload.enable = false;
        sync.enable = true;
        intelBusId = "PCI:0:2:0";
        nvidiaBusId = "PCI:1:0:0";
      };
    };
    nvidia-container-toolkit.enable = true;
  };

  networking = {
    hostName = "odin";
    networkmanager.enable = true;

    firewall = {
      enable = true;
      allowPing = true;
      allowedTCPPorts = [
        # 445 # SAMBA
        # 139 # SAMBA
        # 5357 # SAMBA-WSDD
        8123 # HOME ASSISTANT
        8384 # SYNCTHING
        8385 # SYNCTHING
      ];
      allowedUDPPorts = [
        137 # SYNCTHING
        138 # SYNCTHING
        3702 # SAMBA-WSDD
      ];
      extraCommands = "iptables -t raw -A OUTPUT -p udp -m udp --dport 137 -j CT --helper netbios-ns";
    };
  };

  programs = {
    gamemode = {
      enable = true;
      settings = {
        custom = {
          start = "${pkgs.libnotify}/bin/notify-send 'GameMode started'";
          end = "${pkgs.libnotify}/bin/notify-send 'GameMode ended'";
        };
      };
    };
    gamescope = { enable = true; capSysNice = true; };
    steam.gamescopeSession.enable = true;
  };
  environment.systemPackages = [ pkgs.gnome-tweaks ];
  # services.getty.autologinUser = "tiziano";
  # environment = {
  #   systemPackages = [ pkgs.mangohud ];
  #   loginShellInit =
  #     let
  #       gs = pkgs.writeShellScript "gamescope-init" ''
  #         set -xeuo pipefail
  #         CONNECTOR=*,eDP-1
  #         gamescopeArgs=(
  #             --adaptive-sync # VRR support
  #             # --hdr-enabled
  #             --mangoapp # performance overlay
  #             --rt
  #             --steam
  #             -O
  #             $CONNECTOR
  #         )
  #         steamArgs=(
  #             -pipewire-dmabuf
  #             -tenfoot
  #         )
  #         mangoConfig=(
  #             cpu_temp
  #             gpu_temp
  #             ram
  #             vram
  #         )
  #         mangoVars=(
  #             MANGOHUD=1
  #             MANGOHUD_CONFIG="$(IFS=,; echo "''${mangoConfig[*]}")"
  #         )

  #         export "''${mangoVars[@]}"
  #         exec gamescope "''${gamescopeArgs[@]}" -- steam "''${steamArgs[@]}"
  #       '';
  #     in
  #     ''
  #       [[ "$(tty)" = "/dev/tty1" ]] && ${gs}
  #     '';
  # };

  services = {
    avahi = {
      enable = true;
      openFirewall = true;
      nssmdns4 = true;
      publish = {
        enable = true;
        addresses = true;
        domain = true;
        userServices = true;
        workstation = true;
      };
      extraServiceFiles = {
        ssh = "${pkgs.avahi}/etc/avahi/services/ssh.service";
      };
    };
    blueman.enable = true;
    xserver = {
      displayManager = {
        gdm = { enable = true; autoSuspend = false; };
        autoLogin = { enable = true; user = "tiziano"; };
      };
      desktopManager.gnome.enable = true;
    };
    home-assistant = {
      enable = true;
      openFirewall = true;
      config = {
        default_config = { };

        homeassistant = {
          name = "Casa";
          latitude = "!secret home-latitude";
          longitude = "!secret home-longitude";
          country = "IT";
          elevation = 17;
          unit_system = "metric";
          time_zone = "Europe/Rome";
          external_url = "https://home-assistant.bertof.net";
          allowlist_external_dirs = [ "/tmp" ];
        };

        http = {
          use_x_forwarded_for = true;
          trusted_proxies = [
            hosts.zerotier.ipv4."baldur.zto"
            hosts.tailscale.ipv4."baldur.tsn"
            "::1"
            "127.0.0.1"
          ];
        };

        automation = "!include automations.yaml";
        scene = "!include scenes.yaml";
        alert = "!include alert.yaml";

        alarm_control_panel = {
          platform = "manual";
          code = "!secret alarm_code";
          trigger_time = 60;
        };

        assist_pipeline = { };
        # bluetooth = { };
        camera = [
          # {
          #   platform = "local_file";
          #   file_path = "/tmp/doods_camera_camera_cancello.jpg";
          #   name = "File DOODS2 Camera cancello";
          # }
          # {
          #   platform = "local_file";
          #   file_path = "/tmp/doods_camera_camera_vialetto.jpg";
          #   name = "File DOODS2 Camera vialetto";
          # }
          # {
          #   platform = "local_file";
          #   file_path = "/tmp/doods_camera_camera_garage.jpg";
          #   name = "File DOODS2 Camera garage";
          # }
        ];
        cloud = { };
        config = { };
        # device_tracker = [{
        #   platform = "bluetooth_tracker";
        #   request_rssi = true;
        # }];
        # image_processing = [
        #   {
        #     platform = "doods";
        #     url = "http://localhost:8080";
        #     detector = "default";
        #     source = [
        #       {
        #         entity_id = "camera.camera_camera_cancello";
        #         name = "DOODS2 Camera cancello";
        #       }
        #       {
        #         entity_id = "camera.camera_camera_vialetto";
        #         name = "DOODS2 Camera vialetto";
        #       }
        #       {
        #         entity_id = "camera.camera_camera_garage";
        #         name = "DOODS2 Camera garage";
        #       }
        #     ];
        #     confidence = 60;
        #     file_out = "/tmp/doods_{{ camera_entity.split('.')[1] }}.jpg";
        #     scan_interval = 5;
        #     labels = [
        #       "bicycle"
        #       "car"
        #       "cat"
        #       "dog"
        #       "person"
        #       "truck"
        #     ];
        #   }
        # ];
        # esphome = { };
        frontend = { };
        google_assistant = {
          project_id = "home-assistant-390217";
          report_state = true;
          service_account = "!include google-service-account.json";
          exposed_domains = [
            "alarm_control_panel"
            "button"
            "camera"
            "climate"
            "cover"
            "fan"
            "group"
            "humidifier"
            "input_boolean"
            "input_button"
            "input_select"
            "light"
            "lock"
            "media_player"
            "scene"
            "script"
            "select"
            "switch"
            "vacuum"
          ];
        };
        history = { };
        logbook = { };
        # logger.default = "debug";
        logger.default = "info";
        # "map" = { };
        mobile_app = { };
        notify = [
          # { platform = "telegram"; name = "t_filippo"; chat_id = "!secret filippo_t_chat_id"; }
          # { platform = "telegram"; name = "t_famiglia"; chat_id = "!secret famiglia_t_chat_id"; }
        ];
        recorder.purge_keep_days = 30;
        script = "!include scripts.yaml";
        shopping_list = { };
        sun = { };
        system_health = { };
        # telegram_bot = [{
        #   # platform = "polling";
        #   platform = "webhooks";
        #   api_key = "!secret telegram_api_key";
        #   allowed_chat_ids = [
        #     "!secret filippo_t_chat_id"
        #     "!secret famiglia_t_chat_id"
        #   ];
        # }];
        tts = [
          {
            platform = "google_translate";
            language = "it";
            # tld = "it";
          }
        ];

        smartir = {
          check_updates = false;
        };
        zha = {
          custom_quirks_path = "custom_zha_quirks/";
        };
        climate = [{
          platform = "smartir";
          name = "Climatizzatore";
          unique_id = "climatizzatore";
          device_code = 50;
          controller_data = "switch.tz3290_gnl5a6a5xvql7c2a_ts1201_interruttore";
          temperature_sensor = "sensor.tz3000_fllyghyj_ts0201_temperature";
          humidity_sensor = "sensor.tz3000_fllyghyj_ts0201_humidity";
          power_sensor = "binary_sensor.climatizzatore_acceso";
        }];
      };
      configDir = "/var/lib/hass";
      configWritable = true;
      extraPackages = ps: with ps; [ securetar ];
      customComponents = [
        pkgs.home-assistant-custom-components.smartir
      ];
      extraComponents = [
        "default_config"

        "alert"
        "analytics"
        "androidtv"
        "androidtv_remote"
        "bayesian"
        "binary_sensor"
        "blueprint"
        # "bluetooth_le_tracker"
        # "bluetooth_tracker"
        "button"
        "camera"
        "cast"
        "caldav"
        "calendar"
        "climate"
        "citybikes"
        "configurator"
        # "coronavirus"
        "cover"
        "default_config"
        "derivative"
        "device_automation"
        "device_sun_light_trigger"
        "device_tracker"
        "dlib_face_detect"
        "dlib_face_identify"
        "dlna_dmr"
        "dlna_dms"
        "esphome"
        "flux"
        "gdacs"
        "google"
        "google_translate"
        "group"
        "hassio"
        "jellyfin"
        "local_file"
        "media_player"
        "met"
        "meteoalarm"
        "network"
        # "nextcloud"
        "nmap_tracker"
        "notify"
        "open_meteo"
        "ping"
        "plex"
        "proximity"
        "radarr"
        "radio_browser"
        "random"
        "scene"
        "schedule"
        "script"
        "sonarr"
        "speedtestdotnet"
        "spotify"
        "tcp"
        # "telegram"
        # "telegram_bot"
        "template"
        "threshold"
        "transmission"
        "tod" # times of the day
        "trend"
        "tuya"
        "upnp"
        "wake_on_lan"
        "wled"
        "workday"
        "zha"
        "zoneminder"
      ];
    };
    logind.lidSwitch = "ignore";
    pipewire = {
      enable = true;
      pulse.enable = true;
      jack.enable = true;
      alsa = { enable = true; support32Bit = true; };
    };
    smartd.enable = true;
    thermald.enable = true;
    xserver.videoDrivers = [ "nvidia" ];
  };

  time.timeZone = "Europe/Rome";

  zramSwap.enable = true;

  system.stateVersion = "24.11";
}





