{ config, pkgs, ... }:
let
  nix-build-mail = pkgs.writeShellScript "echo -e \"Content-Type: text/plain\\r\\nSubject: NixOS cache rebuild failed\\r\\n\\r\\nThe nix-rebuild-cache service failed at $(date).\" | sendmail jalle008@proton.me";
in 
{
  # "https://cache.mjallen.dev"
  # "cache.mjallen.dev-1:IzFmKCd8/gggI6lcCXsW65qQwiCLGFFN9t9s2iw7Lvc="
  services.nix-serve = {
    enable = false;
    package = pkgs.nix-serve-ng;
    secretKeyFile = "/etc/nix/cache-priv-key.pem";
    port = 5000;  # Choose your preferred port
    openFirewall = true;
  };
  
  services.atticd = {
    enable = true;
    environmentFile = config.sops.secrets."jallen-nas/attic-key".path;
    settings = {
      listen = "[::]:9012";
    };
  };

  # Improved systemd service with better error handling
  systemd = {
    services = {
      attic-watch-store = {
        enable = true;
        description = "watch store for cache";
        serviceConfig = {
          Type = "simple";
          User = "admin";
          Group = "jallen-nas";
          WorkingDirectory = "/etc/nixos";
          StandardOutput = "journal+console";
          StandardError = "journal+console";
          Restart = "always";
          restartSec = "5";
        };
        path = with pkgs; [
          bash
          attic-client
        ];
        script = ''
        #!/usr/bin/env bash
        attic watch-store nas-cache
        '';
      };
  
      nix-rebuild-cache-desktop = {
        enable = true;
        description = "Rebuild desktop NixOS configurations for cache";
        serviceConfig = {
          Type = "oneshot";
          User = "admin";
          Group = "jallen-nas";
          WorkingDirectory = "/etc/nixos";
          StandardOutput = "journal+console";
          StandardError = "journal+console";
          Restart = "no";
          # Increase timeout for large builds
          TimeoutStartSec = "2h";
        };
        path = with pkgs; [
          nix
          git
          uutils-coreutils
          gnugrep
          gnused
          openssh
        ];
        script = ''
          #!/usr/bin/env bash
          
          # Pull latest changes if in a git repo
          if [ -d .git ]; then
            git pull || echo "Warning: Could not pull latest changes"
          fi
          
          echo "Starting build of matt-nixos at $(date)"
          if nix flake update desktop-nixpkgs desktop-chaotic desktop-home-manager desktop-impermanence desktop-lanzaboote desktop-nixos-hardware desktop-sops-nix desktop-steam-rom-manager nixpkgs-unstable nixpkgs-stable nix-darwin; then
            echo "matt-nixos flake updated successfully at $(date)"
          else
            echo "matt-nixos failed to build at $(date)"
          fi
          if nix build .\#nixosConfigurations.matt-nixos.config.system.build.toplevel --no-link; then
            echo "matt-nixos built successfully at $(date)"
            git add .
            git commit -m "Desktop Updates $(date)"
          else
            echo "matt-nixos failed to build at $(date)"
            git reset --hard
          fi
        '';
      };
      nix-rebuild-cache-steamdeck = {
        enable = true;
        description = "Rebuild steamdeck NixOS configurations for cache";
        serviceConfig = {
          Type = "oneshot";
          User = "admin";
          Group = "jallen-nas";
          WorkingDirectory = "/etc/nixos";
          StandardOutput = "journal+console";
          StandardError = "journal+console";
          Restart = "no";
          # Increase timeout for large builds
          TimeoutStartSec = "2h";
        };
        path = with pkgs; [
          nix
          git
          uutils-coreutils
          gnugrep
          gnused
          openssh
        ];
        script = ''
          #!/usr/bin/env bash
          
          # Pull latest changes if in a git repo
          if [ -d .git ]; then
            git pull || echo "Warning: Could not pull latest changes"
          fi
          
          echo "Starting build of steamdeck at $(date)"
          if nix flake update steamdeck-nixpkgs steamdeck-chaotic steamdeck-home-manager steamdeck-impermanence steamdeck-jovian steamdeck-lanzaboote steamdeck-nixos-hardware steamdeck-sops-nix steamdeck-steam-rom-manager; then
            echo "steamdeck flake updated successfully at $(date)"
          else
            echo "steamdeck flake failed to update at $(date)"
            git reset --hard
          fi
          if nix build .\#nixosConfigurations.steamdeck.config.system.build.toplevel --no-link; then
            echo "steamdeck built successfully at $(date)"
            git add .
            git commit -m "Steamdeck Updates $(date)"
          else
            echo "steamdeck failed to build at $(date)"
            git reset --hard
          fi
        '';
      };
      nix-rebuild-cache-pi4 = {
        enable = true;
        description = "Rebuild pi4 NixOS configurations for cache";
        serviceConfig = {
          Type = "oneshot";
          User = "admin";
          Group = "jallen-nas";
          WorkingDirectory = "/etc/nixos";
          StandardOutput = "journal+console";
          StandardError = "journal+console";
          Restart = "no";
          # Increase timeout for large builds
          TimeoutStartSec = "2h";
        };
        path = with pkgs; [
          nix
          git
          uutils-coreutils
          gnugrep
          gnused
          openssh
        ];
        script = ''
          #!/usr/bin/env bash
          
          # Pull latest changes if in a git repo
          if [ -d .git ]; then
            git pull || echo "Warning: Could not pull latest changes"
          fi
          
          echo "Starting build of pi4 at $(date)"
          if nix flake update pi4-nixpkgs pi4-home-manager pi4-impermanence pi4-sops-nix pi4-nixos-hardware pi4-nixos-raspberrypi pi4-disko; then
            echo "pi4 flake updated successfully at $(date)"
          else
            echo "pif flake failed to update at $(date)"
          fi
          if nix build .\#nixosConfigurations.pi4.config.system.build.toplevel --no-link --impure; then
            echo "pi4 built successfully at $(date)"
            git add .
            git commit -m "Pi4 Updates $(date)"
          else
            echo "pi4 failed to build at $(date)"
            git reset --hard
          fi
        '';
      };
      nix-rebuild-cache-pi5 = {
        enable = true;
        description = "Rebuild pi5 NixOS configurations for cache";
        serviceConfig = {
          Type = "oneshot";
          User = "admin";
          Group = "jallen-nas";
          WorkingDirectory = "/etc/nixos";
          StandardOutput = "journal+console";
          StandardError = "journal+console";
          Restart = "no";
          # Increase timeout for large builds
          TimeoutStartSec = "2h";
        };
        path = with pkgs; [
          nix
          git
          uutils-coreutils
          gnugrep
          gnused
          openssh
        ];
        script = ''
          #!/usr/bin/env bash
          
          # Pull latest changes if in a git repo
          if [ -d .git ]; then
            git pull || echo "Warning: Could not pull latest changes"
          fi
          
          echo "Starting build of pi5 at $(date)"
          if nix flake update pi5-nixpkgs pi5-home-manager pi5-impermanence pi5-nixos-hardware pi5-sops-nix nixos-raspberrypi; then
            echo "pi5 flake updated successfully at $(date)"
          else
            echo "pi5 flake failed to update at $(date)"
          fi
          if nix build .\#nixosConfigurations.pi5.config.system.build.toplevel --no-link; then
            echo "pi5 built successfully at $(date)"
            git add .
            git commit -m "Pi5 Updates $(date)"
          else
            echo "pi5 failed to build at $(date)"
            git reset --hard
          fi
        '';
      };
      nix-rebuild-cache-nas = {
        enable = true;
        description = "Rebuild nas NixOS configurations for cache";
        serviceConfig = {
          Type = "oneshot";
          User = "admin";
          Group = "jallen-nas";
          WorkingDirectory = "/etc/nixos";
          StandardOutput = "journal+console";
          StandardError = "journal+console";
          Restart = "no";
          # Increase timeout for large builds
          TimeoutStartSec = "2h";
        };
        path = with pkgs; [
          nix
          git
          uutils-coreutils
          gnugrep
          gnused
          openssh
        ];
        script = ''
          #!/usr/bin/env bash
          
          # Pull latest changes if in a git repo
          if [ -d .git ]; then
            git pull || echo "Warning: Could not pull latest changes"
          fi
          
          echo "Starting build of jallen-nas at $(date)"
          if nix flake update nas-nixpkgs nas-authentik-nix nas-cosmic nas-crowdsec nas-home-manager nas-impermanence nas-lanzaboote nas-nixos-hardware nas-sops-nix; then
            echo "jallen-nas flake updated successfully at $(date)"
          else
            echo "jallen-nas flake failed to update at $(date)"
          fi
          export NIXPKGS_ALLOW_UNFREE=1
          if nix build .\#nixosConfigurations.jallen-nas.config.system.build.toplevel --no-link --impure; then
            echo "jallen-nas built successfully at $(date)"
            git add .
            git commit -m "Jallen-NAS Updates $(date)"
          else
            echo "jallen-nas failed to build at $(date)"
            git reset --hard
          fi
        '';
      };
    };

    timers = {
      nix-rebuild-cache-desktop = {
        description = "Timer for rebuilding desktop NixOS configurations cache";
        wantedBy = [ "timers.target" ];
        timerConfig = {
          OnCalendar = "weekly";
          Persistent = true;
          RandomizedDelaySec = "24h";
        };
      };
      nix-rebuild-cache-steamdeck = {
        description = "Timer for rebuilding steamdeck NixOS configurations cache";
        wantedBy = [ "timers.target" ];
        timerConfig = {
          OnCalendar = "weekly";
          Persistent = true;
          RandomizedDelaySec = "24h";
        };
      };
      nix-rebuild-cache-pi4 = {
        description = "Timer for rebuilding pi4 NixOS configurations cache";
        wantedBy = [ "timers.target" ];
        timerConfig = {
          OnCalendar = "weekly";
          Persistent = true;
          RandomizedDelaySec = "24h";
        };
      };
      nix-rebuild-cache-pi5 = {
        description = "Timer for rebuilding pi5 NixOS configurations cache";
        wantedBy = [ "timers.target" ];
        timerConfig = {
          OnCalendar = "weekly";
          Persistent = true;
          RandomizedDelaySec = "24h";
        };
      };
      nix-rebuild-cache-nas = {
        description = "Timer for rebuilding nas NixOS configurations cache";
        wantedBy = [ "timers.target" ];
        timerConfig = {
          OnCalendar = "weekly";
          Persistent = true;
          RandomizedDelaySec = "24h";
        };
      };
    };
  };

  nix = {
    settings.builders-use-substitutes = true;
    distributedBuilds = true;
    buildMachines = [
      {
        hostName = "pi5.local";
        system = "aarch64-linux";
        maxJobs = 4;
        sshUser = "matt";
        supportedFeatures = [ "nixos-test" "benchmark" "big-parallel" "kvm" ];
      }
    ];
  };
}
