{ pkgs }:
pkgs.writeShellApplication {
  name = "nr";

  runtimeInputs = with pkgs; [
    nix-output-monitor
    openssh
    coreutils
    nix
    attic-client
  ];

  text = ''
    set -e

    TARGET_NAME="''${1:-$(hostname)}"
    FLAKE_PATH="."
    UPLOAD_CACHE=true

    while [[ $# -gt 0 ]]; do
      case "$1" in
        --no-upload) UPLOAD_CACHE=false ;;
        *) TARGET_NAME="$1" ;;
      esac
      shift
    done

    EXTRA_BUILD_FLAGS=()
    if [ "$TARGET_NAME" = "kazusa" ]; then
      EXTRA_BUILD_FLAGS+=("--max-substituter-jobs" "2")
    fi

    echo "시스템 빌드 중... $TARGET_NAME"
    # shellcheck disable=SC2086
    BUILD_PATH=$(nom build "$FLAKE_PATH#nixosConfigurations.$TARGET_NAME.config.system.build.toplevel" \
      "''${EXTRA_BUILD_FLAGS[@]}" \
      --print-out-paths --no-link)

    echo "스위치 중..."
    sudo nix-env --profile /nix/var/nix/profiles/system --set "$BUILD_PATH"
    sudo "$BUILD_PATH/bin/switch-to-configuration" switch

    if [ "$UPLOAD_CACHE" = true ]; then
      echo "캐시 업로드 중..."
      attic push imnyang "$BUILD_PATH" || echo "푸시 실패"
    fi

    echo "스위치 완료!"
  '';
}