#!/usr/bin/env bash

# A restored download store is enough for a locked install: the lockfile's
# checksum names the stored file, and a file that no longer matches it is not
# used.

export MISE_LOCKFILE=1

detect_platform
PLATFORM="$MISE_PLATFORM"

SRV="$PWD/srv"
mkdir -p "$SRV"
printf '#!/bin/sh\necho locked store ok\n' >"$SRV/mytool"
SHA="$(sha256sum "$SRV/mytool" | cut -d' ' -f1)"

start_http_server --dir "$SRV"

cat >mise.toml <<EOF
[tools."http:locked-store"]
version = "1.0.0"
bin = "mytool"
url = "http://127.0.0.1:${HTTP_PORT}/mytool"
checksum = "sha256:${SHA}"
EOF

mise lock --platform "$PLATFORM"
assert_contains "cat mise.lock" "sha256:${SHA}"
mise install --locked
assert_contains "mise x -- mytool" "locked store ok"

# Only the download store is kept: no installs, no server.
kill "$HTTP_SERVER_PID"
mise uninstall http:locked-store@1.0.0
assert_fail "test -d $MISE_DATA_DIR/installs/http-locked-store/1.0.0"
mise install --locked
assert_contains "mise x -- mytool" "locked store ok"

# A stored file that was changed is not installed.
BLOB="$(find "$MISE_CACHE_DIR/downloads-cas/blobs" -type f | head -1)"
mise uninstall http:locked-store@1.0.0
printf tampered >>"$BLOB"
assert_fail "mise install --locked"
assert_fail "test -d $MISE_DATA_DIR/installs/http-locked-store/1.0.0"
