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

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

  text = ''
    set -e

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

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

    echo "macOS 시스템 빌드 중... ($TARGET_NAME)"

    BUILD_PATH=$(nom build "$FLAKE_PATH#darwinConfigurations.$TARGET_NAME.system" --print-out-paths --no-link)

    echo "프로필 등록 및 스위치 중..."

    sudo nix-env --profile /nix/var/nix/profiles/system --set "$BUILD_PATH"

    sudo "$BUILD_PATH/activate"

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

    echo "nix-darwin 스위치 완료!"
  '';
}
