module RbSys::Mkmf

def optional_rust_toolchain(builder)

def optional_rust_toolchain(builder)
  <<~MAKE
    #{conditional_assign("RB_SYS_FORCE_INSTALL_RUST_TOOLCHAIN", builder.force_install_rust_toolchain)}
    # Only run if the we are told to explicitly install the Rust toolchain
    #{if_neq_stmt("$(RB_SYS_FORCE_INSTALL_RUST_TOOLCHAIN)", "false")}
    #{conditional_assign("RB_SYS_RUSTUP_PROFILE", "minimal")}
    # If the user passed true, we assume stable Rust. Otherwise, use what
    # was specified (i.e. RB_SYS_FORCE_INSTALL_RUST_TOOLCHAIN=beta)
    #{if_eq_stmt("$(RB_SYS_FORCE_INSTALL_RUST_TOOLCHAIN)", "true")}
      RB_SYS_FORCE_INSTALL_RUST_TOOLCHAIN = stable
    #{endif_stmt}
    # If a $RUST_TARGET is specified (i.e. for rake-compiler-dock), append
    # that to the profile.
    #{if_eq_stmt("$(RUST_TARGET)", "")}
      RB_SYS_DEFAULT_TOOLCHAIN = $(RB_SYS_FORCE_INSTALL_RUST_TOOLCHAIN)
    #{else_stmt}
      RB_SYS_DEFAULT_TOOLCHAIN = $(RB_SYS_FORCE_INSTALL_RUST_TOOLCHAIN)-$(RUST_TARGET)
    #{endif_stmt}
    #{conditional_assign("CARGO_HOME", "$(RB_SYS_BUILD_DIR)/$(RB_SYS_DEFAULT_TOOLCHAIN)/cargo", export: true)}
    #{conditional_assign("RUSTUP_HOME", "$(RB_SYS_BUILD_DIR)/$(RB_SYS_DEFAULT_TOOLCHAIN)/rustup", export: true)}
    #{export_env("PATH", "$(CARGO_HOME)/bin:$(RUSTUP_HOME)/bin:$(PATH)")}
    #{export_env("RUSTUP_TOOLCHAIN", "$(RB_SYS_DEFAULT_TOOLCHAIN)")}
    #{export_env("CARGO", "$(CARGO_HOME)/bin/cargo")}
    $(CARGO): 
    \t$(Q) $(MAKEDIRS) $(CARGO_HOME) $(RUSTUP_HOME)
    \tcurl --proto '=https' --tlsv1.2 --retry 10 --retry-connrefused -fsSL "https://sh.rustup.rs" | sh -s -- --no-modify-path --profile $(RB_SYS_RUSTUP_PROFILE) --default-toolchain none -y
    \trustup toolchain install $(RB_SYS_DEFAULT_TOOLCHAIN) --profile $(RB_SYS_RUSTUP_PROFILE)
    \trustup default $(RB_SYS_DEFAULT_TOOLCHAIN)
    $(RUSTLIB): $(CARGO)
    #{endif_stmt}
  MAKE
end