# This is your system's configuration file.
# Use this to configure your system environment (it replaces /etc/nixos/configuration.nix)
{
  inputs,
  lib,
  config,
  pkgs,
  myhostname,
  ...
}:
let
  modulesDirectory = ../../moduler;
  backupScript = pkgs.writeShellScript "rclone-backups" ''
    set -euo pipefail

    declare -A SOURCES=(
      [vaultwarden]="/var/lib/vaultwarden/"
      [tailscale]="/var/lib/tailscale/"
      [kitchenowl]="/var/lib/kitchenowl/"
    )

    REMOTE_BASE="gdrive:backups"
    NOW="$(date +%Y-%m-%d_%H%M)"

    for name in "''${!SOURCES[@]}"; do
      SRC="''${SOURCES[$name]}"
      DEST="''${REMOTE_BASE}/''${name}/''${NOW}"

      rclone copy "''${SRC}" "''${DEST}" --create-empty-src-dirs \
        --config /root/.config/rclone/rclone.conf

      mapfile -t dirs < <(
        rclone lsf "''${REMOTE_BASE}/''${name}" --dirs-only --format p \
          --config /root/.config/rclone/rclone.conf | sort
      )

      if [ "''${#dirs[@]}" -gt 7 ]; then
        remove_count=$(( ''${#dirs[@]} - 7 ))
        for d in "''${dirs[@]:0:''${remove_count}}"; do
          rclone purge "''${REMOTE_BASE}/''${name}/''${d%/}" \
            --config /root/.config/rclone/rclone.conf
        done
      fi
    done
  '';
in
{
  # You can import other NixOS modules here
  imports = [
    ./hardware-configuration.nix

    (modulesDirectory + /users.nix)
    (modulesDirectory + /kitchenowl.nix)
    # (modulesDirectory + /radicale.nix)
    (modulesDirectory + /vaultwarden.nix)
    (modulesDirectory + /uptime-kuma.nix)
    (modulesDirectory + /wedding.nix)

    (modulesDirectory + /services/base)
    (modulesDirectory + /services/monitoring)
    (modulesDirectory + /services/headscale)
    (modulesDirectory + /services/mpd)
    (modulesDirectory + /services/actual)
    (modulesDirectory + /services/forgejo)
    (modulesDirectory + /services/wishlist)
    (modulesDirectory + /services/glance)
    (modulesDirectory + /services/gotify)
    (modulesDirectory + /services/kanboard)
    (modulesDirectory + /services/immich)
    (modulesDirectory + /services/paperless)
    (modulesDirectory + /services/filebrowser)
    (modulesDirectory + /services/mediamtx)
  ];

  sops.defaultSopsFile = ../../secrets/sops.yaml;
  sops.age.sshKeyPaths = [ "/etc/ssh/ssh_host_ed25519_key" ];
  sops.secrets.gandi_key = {
    path = "/run/secrets/gandi_key";
    owner = "root";
    mode = "0440";
  };
  environment.systemPackages = with pkgs; [
    git
    vim
    rsync
    rclone
    fuse
  ];

  programs.fuse.userAllowOther = true;

  systemd.tmpfiles.rules = [
    "d /mnt/gdrive 0755 root root - -"
    "d /mnt/gdrive/backups 0755 root root - -"
  ];

  systemd.services.rclone-gdrive = {
    description = "Rclone mount for Google Drive";
    after = [ "network-online.target" ];
    wants = [ "network-online.target" ];
    serviceConfig = {
      Type = "simple";
      ExecStart = ''
        ${pkgs.rclone}/bin/rclone mount \
          gdrive: /mnt/gdrive \
          --config /root/.config/rclone/rclone.conf \
          --allow-other \
          --dir-cache-time 12h \
          --vfs-cache-mode writes
      '';
      ExecStop = "${pkgs.fuse}/bin/fusermount -u /mnt/gdrive";
      Restart = "on-failure";
      RestartSec = "10s";
    };
    wantedBy = [ "multi-user.target" ];
  };

  systemd.services.rsync-backups = {
    description = "Rclone snapshot backups to Google Drive";
    serviceConfig = {
      Type = "oneshot";
      ExecStart = backupScript;
      User = "root";
    };
    after = [ "network-online.target" ];
    wants = [ "network-online.target" ];
    path = [
      pkgs.coreutils
      pkgs.findutils
      pkgs.rclone
    ];
  };

  systemd.timers.rsync-backups = {
    wantedBy = [ "timers.target" ];
    timerConfig = {
      OnCalendar = "*-*-* 00,06,12,18:00:00";
      Persistent = true;
    };
  };

  home-manager.users.fw = {
    # imports = [
    #   (modulesDirectory + /programs/beets)
    # ];
    home.username = "fw";
    home.homeDirectory = "/home/fw";

    home.stateVersion = "26.05";

    systemd.user.startServices = "sd-switch";
  };

  services.nginx = {
    enable = true;
    recommendedProxySettings = true;
    recommendedTlsSettings = true;
    virtualHosts."router.wastring.com" = {
      enableACME = true;
      forceSSL = true;
      locations."/" = {
        proxyPass = "https://192.168.1.1";
        proxyWebsockets = true;
        extraConfig = "proxy_ssl_server_name on;" + "proxy_pass_header Authorization;";
      };
    };
  };

  immich = {
    enable = true;
  };
  paperless = {
    enable = false;
  };
  kanboard = {
    enable = true;
    host = "127.0.0.1";
    port = 3128;
    domain = "kanboard.wastring.com";
  };
  gotify = {
    enable = true;
    host = "127.0.0.1";
    port = 8121;
    domain = "message.wastring.com";
  };
  filebrowser = {
    enable = false;
    host = "127.0.0.1";
    port = 8126;
    domain = "files.wastring.com";
  };
  mediamtx = {
    enable = true;
    host = "0.0.0.0";
    rtspPort = 8554;
  };
  glance = {
    enable = false;
    host = "127.0.0.1";
    domain = "home.wastring.com";
  };
  wishlist = {
    enable = true;
    host = "127.0.0.1";
    domain = "wish.wastring.com";
  };

  wedding = {
    enable = true;
  };

  forgejo = {
    enable = false;
  };

  actual = {
    enable = true;
  };

  # grafana = {
  #   enable = true;
  #   host = "127.0.0.1";
  #   domain = "grafana.wastring.com";
  # };

  headscale = {
    enable = true;
  };

  prometheus = {
    enable = false;
    exporters.enable = true;
  };

  loki = {
    enable = false;
  };

  alloy = {
    enable = false;
    configPath = ./alloy-systemd.yaml;
  };

  nix.settings = {
    trusted-public-keys = [
      "cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY="
      "hyprland.cachix.org-1:a7pgxzMz7+chwVL3/pzj6jIBMioiJM7ypFP8PwtkuGc="
    ];
    require-sigs = false;
  };

  security.sudo.wheelNeedsPassword = false;
  users.users.root.openssh.authorizedKeys.keys = [
    "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDALsdpwvC0w/Aj+1fWtzJyyWoUrGkdh8o2thVHeQQBNo0D7cmVberYmi4Cv9gWGX6PaElrnOl0KRdGyro2wxOYokSxgk2VgWW67BFITAQAbKyG2NhXXPbhb4jccDo7WH7TtOG8IofuJTPRu1Duda6k4RN0I0CkyAN6LGX+zy49cq0qKf9ijXYhCDYNih3+Fu/ig0aW/SYmsVoUl2VFTWdI5x5/wLvIjTEZhmAtYIeYADaLnom356cFrUysZa++FUujQAz3Ow236BvP95XZdTsqvfWNZFNIpC9VYF72JeIDCs5wDIr0GFmanF2On1nar+jJpoOE8SdHt357p5g/PqXV5TisN2xQRkqVwO9tWtMl4sF84jA4ULnY2gQWv9jErMxymUQ1IwuPUzDDlbRHCtfexAtkBy7wv6xslKAzG1QahvF/btNs5Caj3LN31rgAuxyooCbKGKTeBP3kHPKcz1iupgidfbO/QqVXBRQJTEdGyAKa8hVmLQZZPC/XUhxESAk= fw@fw-nix"
    "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC8ku8iCb7tXd/tfxYDW+Tj8K9kpfrYZciYUZ6tBpO80inm4EImtfyEeJTuqDWMKov2BftUKs8brNeTBCXUEvU1P0+cpOP9RtYA5tfBXf3su+iVSswJJStIxNboXHrEGKdJJRNsTv/9agshDSUBy6G5TI1cXhv/updornfA4fwOMqOmtlYEn6XCRnsrO6NBLc/uLckdbF75HOsoLvezRvuqTLjpapjaUKGVPrgNXiclIKHmuOx71kgD4FX3rSz9FgKjnfu3a7DBbrHsf/g+N9PjNF1muN9UOV6nK3WwiO9BMWi7NpAWfzJOeZg9chqzI+U6CcsqYVeESgL41so+dnv3 fw@laptop"
    "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIP34dnsZSnWdDvd+3BXDwcw7wP0PjPEx2eCdBQJyGD6O fw@laptop"
    "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAII60tdNsG0z9q2jHmoTKvkeLQE6OF0bmTsDX1bpqpoG7 fw@jobb"
  ];

  networking.hostName = myhostname;

  system.stateVersion = "25.05";
}
