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

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

  text = ''
    set -e

    TARGET_NAME=""
    if [ $# -gt 0 ]; then
      TARGET_NAME="$1"
    fi
    FLAKE_PATH="."

    declare -A HOST_MAP
    HOST_MAP["hikari"]="10.11.8.100"
    HOST_MAP["hako"]="10.11.8.102"
    HOST_MAP["kazusa"]="82.21.82.30"
    HOST_MAP["natsu"]="natsu.icn.mizuki.guru"

    HOST_MAP["mafuyu"]="10.20.30.101"
    HOST_MAP["mizuki"]="10.20.30.103"
    HOST_MAP["ena"]="10.20.30.104"

    if [ -z "$TARGET_NAME" ]; then
      echo "nrr - 로컬에서 NixOS 빌드 후 스위치합니다"
      echo "사용법: nrr <hostname>"
      exit 1
    fi

    if [[ -v "HOST_MAP[$TARGET_NAME]" ]]; then
      TARGET_IP=''${HOST_MAP[$TARGET_NAME]}
      echo "호스트 사용: $TARGET_NAME -> $TARGET_IP"
    else
      echo "매핑되지 않은 호스트입니다."
      exit 1
    fi

    echo "시스템 빌드 중..."
    BUILD_PATH=$(nom build "$FLAKE_PATH#nixosConfigurations.$TARGET_NAME.config.system.build.toplevel" --print-out-paths --no-link --eval-cache --accept-flake-config)

    echo "시스템 복사 중... ($BUILD_PATH -> $TARGET_IP)"
    nix copy --to "ssh://imnyang@$TARGET_IP" "$BUILD_PATH"

    echo "스위치 중..."
    # shellcheck disable=SC2029
    ssh "imnyang@$TARGET_IP" "sudo nix-env --profile /nix/var/nix/profiles/system --set \"$BUILD_PATH\" && sudo $BUILD_PATH/bin/switch-to-configuration switch"

    echo "캐시 업로드 중..."
    attic push imnyang "$BUILD_PATH" || echo "푸시 실패"

    echo "배포 완료!"
  '';
}
