#!/usr/bin/env bash
# A download that does not match the checksum in mise.lock is refused before it
# is unpacked, so nothing of it is left where later commands look for the tool.
#
# `cli/1.2.3` matters: the http backend installs it under a hashed directory name
# (`cli-1.2.3-<hash>`), which is not the path the generic cleanup removes after a
# failed install.

set -euo pipefail

export MISE_LOCKFILE=1 MISE_OFFLINE=1

ARTIFACT="$PWD/mirror/tool"
mkdir -p mirror

for version in 1.2.3 cli/1.2.3; do
  printf '#!/bin/sh\necho genuine\n' >"$ARTIFACT"
  cat >mise.toml <<EOF
[tools."http:lock-order-tool"]
version = "$version"
bin = "tool"
url = "file://$ARTIFACT"
EOF
  rm -f mise.lock
  touch mise.lock

  # The first install pins the genuine file's checksum.
  mise install
  assert_contains "cat mise.lock" "checksum = "
  assert "mise x -- tool" "genuine"
  mise uninstall --all http:lock-order-tool

  # The mirror now serves other bytes.
  printf '#!/bin/sh\necho tampered\n' >"$ARTIFACT"
  assert_fail "mise install" "Checksum mismatch"
  assert_directory_not_exists "$MISE_DATA_DIR/installs/http-lock-order-tool"
  assert_contains "mise ls http:lock-order-tool" "(missing)"
  assert_fail "mise install --locked" "Checksum mismatch"
done
