{
  config,
  pkgs,
  ...
}:
let
  hostname = config.networking.hostName;
  flakeDir = "/tmp/nixos-infra-flake";
  updateScript = pkgs.writeShellScriptBin "nixos-update" ''
    #!/usr/bin/env bash
    set -euo pipefail

    FLAKE_URL="ssh://forgejo@git.ruject.fun/RuJect/nixos-infra.git"
    FLAKE_DIR="${flakeDir}"
    REBUILD_CMD="nh os switch $FLAKE_DIR -H ${hostname}"

    echo "→ Updating flake from git.ruject.fun..."

    if [[ ! -d "$FLAKE_DIR/.git" ]]; then
        echo "→ Cloning $FLAKE_DIR ..."
        git clone --depth=1 "$FLAKE_URL" "$FLAKE_DIR"
    else
        echo "→ Repository $FLAKE_DIR already exists, updating..."
        git -C "$FLAKE_DIR" fetch --depth=1
        git -C "$FLAKE_DIR" reset --hard FETCH_HEAD
    fi

    echo "→ Will run:"
    echo "    $REBUILD_CMD"

    read -r -p "→ Continue? [Y/n] " answer
    case "$answer" in
        [Yy]*|"")
            echo "→ Running..."
            $REBUILD_CMD
            ;;
        *)
            echo "→ Cancelled by user."
            exit 0
            ;;
    esac

    echo
    echo "→ Done."
  '';
in
{
  environment.systemPackages = [
    updateScript
  ];

  environment.interactiveShellInit = ''
    echo "For update system use command:  nixos-update"
  '';
}
