#!/usr/bin/env bash

# A download pinned by a checksum is kept by that checksum and reused, but only
# while it still hashes to the pin.

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

start_http_server --dir "$SRV"

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

mise install
assert_contains "mise x -- mytool" "cached tool ok"

ENTRY="$MISE_CACHE_DIR/downloads-cas/pins/sha256/$SHA.json"
assert "test -f $ENTRY && echo kept" "kept"
BLOB="$(find "$MISE_CACHE_DIR/downloads-cas/blobs" -type f | head -1)"

# Without a pin, the server is asked whether the kept download is still current.
printf '#!/bin/sh\necho unpinned tool ok\n' >"$SRV/mytool2"
touch -d '2020-01-01' "$SRV/mytool2"
cat >mise.toml <<EOF
[tools."http:cas-unpinned"]
version = "1.0.0"
bin = "mytool2"
url = "http://127.0.0.1:${HTTP_PORT}/mytool2"
EOF
mise install
assert_contains "mise x -- mytool2" "unpinned tool ok"
assert "ls $MISE_CACHE_DIR/downloads-cas/urls | wc -l | tr -d ' '" "1"
mise uninstall http:cas-unpinned@1.0.0
mise install
assert_contains "mise x -- mytool2" "unpinned tool ok"
cat >mise.toml <<EOF
[tools."http:cas-tool"]
version = "1.0.0"
bin = "mytool"
url = "http://127.0.0.1:${HTTP_PORT}/mytool"
checksum = "sha256:${SHA}"
EOF

# With the server gone, a reinstall is served from the kept download.
kill "$HTTP_SERVER_PID"
mise uninstall http:cas-tool@1.0.0
assert_fail "test -d $MISE_DATA_DIR/installs/http-cas-tool/1.0.0"
mise install
assert_contains "mise x -- mytool" "cached tool ok"

# A kept file that no longer matches is never installed. The server is down, so
# the install fails, and the pin entry that pointed at it is removed.
printf tampered >>"$BLOB"
mise uninstall http:cas-tool@1.0.0
assert_fail "mise install"
assert_fail "test -f $ENTRY"
