#!/usr/bin/env bash

# Rustup is available in debian and will install the latest rustc and cargo

DEST=${1:-/etc/skel}
RUSTUP_HOME=${DEST}/.rustup
CARGO_HOME=${DEST}/.cargo

sudo apt install rustup lldb # cargo-debstatus

if [[ -d ${RUSTUP_HOME} ]]; then
  mv "${RUSTUP_HOME}" "${RUSTUP_HOME}-backup"
fi

if [[ -d ${CARGO_HOME} ]]; then
  mv "${CARGO_HOME}" "${CARGO_HOME}-backup"
fi

mkdir -p "${DEST}/.cargo" "${DEST}/.rustup"
# sudo chown -R $(whoami) ${DEST}/.cargo ${DEST}/.rustup

# Add env to zsh
# https://doc.rust-lang.org/cargo/reference/environment-variables.html
conf_print_cargo_env_zshrc() {
  cat <<EOF
RUSTUP_HOME=${DEST}/.rustup
CARGO_HOME=${DEST}/.cargo
EOF
}
conf_print_cargo_env_zshrc | tee -a "${DEST}/.zshrc/004_cargo_env"

# RUSTC_BOOTSTRAP = "1" allows nightly features; use cautiously.
conf_print_cargo_config() {
  cat <<EOF
[env]
RUSTC_BOOTSTRAP = "0"

[registries.crates-io]
protocol = "sparse"

[net]
git-fetch-with-cli = true
EOF
}
conf_print_cargo_config | tee "${CARGO_HOME}/config.toml"

## add this to ./cargo/config.toml
conf_print_use_debian_packages() {
  cat <<EOF

# [source.debian-packages]
# directory = "/usr/share/cargo/registry"
# [source.crates-io]
# replace-with = "debian-packages"
EOF
}
conf_print_use_debian_packages | tee -a "${CARGO_HOME}/config.toml"

conf_print_rustup_config() {
  cat <<EOF
default_toolchain = "stable-x86_64-unknown-linux-gnu"
profile = "default"
version = "12"

[overrides]
EOF
}
conf_print_rustup_config | tee "${RUSTUP_HOME}/settings.toml"

rustup default stable

rustup update

rustc --version
cargo --version
rustup show

# A TUI to assist in cleaning build artifacts.
cargo install cargo-cleaner
