#!/usr/bin/env bash

cat >~/bin/cargo <<'EOS'
#!/usr/bin/env bash
while (($#)); do
  if [[ $1 == "--root" ]]; then
    mkdir -p "$2/bin"
    printf '#!/bin/sh\necho hi\n' >"$2/bin/orig-bin"
    chmod +x "$2/bin/orig-bin"
    exit 0
  fi
  shift
done
EOS
chmod u+x ~/bin/cargo
export PATH="$HOME/bin:$PATH"
export MISE_CARGO_BINSTALL=0

cat >mise.toml <<'EOS'
[tools]
"cargo:rename-test" = { version = "1.0.0", bin = "orig-bin", rename_exe = "renamed-bin" }
EOS
mise install
install_path="$(mise where cargo:rename-test@1.0.0)"
assert "test -x '$install_path/bin/renamed-bin' && echo ok" "ok"
assert "test ! -e '$install_path/bin/orig-bin' && echo ok" "ok"

# Changing rename_exe must reinstall with the new name.
cat >mise.toml <<'EOS'
[tools]
"cargo:rename-test" = { version = "1.0.0", bin = "orig-bin", rename_exe = "other-bin" }
EOS
mise install
assert "test -x '$install_path/bin/other-bin' && echo ok" "ok"
assert "test ! -e '$install_path/bin/renamed-bin' && echo ok" "ok"

# Removing rename_exe must restore the original name.
cat >mise.toml <<'EOS'
[tools]
"cargo:rename-test" = { version = "1.0.0", bin = "orig-bin" }
EOS
mise install
assert "test -x '$install_path/bin/orig-bin' && echo ok" "ok"
assert "test ! -e '$install_path/bin/other-bin' && echo ok" "ok"
