#!/usr/bin/env bash

# Secret values must not be copied into shell state, and must not reach the env cache.

export MISE_ENV_CACHE=1
export __MISE_ENV_CACHE_KEY="dGVzdGtleXRlc3RrZXl0ZXN0a2V5dGVzdGtleXRlc3Q="

cat >"$MISE_CONFIG_DIR/config.toml" <<TOML
[env]
PLAIN_VAR = "plain-value-marker"
API_TOKEN = { value = "s3cr3t-marker", redact = true }
TOML

# prints the decompressed msgpack of a __MISE_DIFF / __MISE_SESSION blob
decode_state() {
  python3 -c '
import base64, sys, zlib
raw = sys.argv[1]
sys.stdout.buffer.write(zlib.decompress(base64.b64decode(raw + "=" * (-len(raw) % 4))))
' "$1" | tr -c '[:print:]' ' '
}

out="$(mise hook-env -s bash --force)"
diff_blob="$(sed -n "s/^export __MISE_DIFF=//p" <<<"$out")"
session_blob="$(sed -n "s/^export __MISE_SESSION=//p" <<<"$out")"
[ -n "$diff_blob" ] || fail "no __MISE_DIFF in hook-env output: $out"
[ -n "$session_blob" ] || fail "no __MISE_SESSION in hook-env output: $out"

# keys are tracked, values are not
export DECODED_DIFF DECODED_SESSION
DECODED_DIFF="$(decode_state "$diff_blob")"
DECODED_SESSION="$(decode_state "$session_blob")"
for var in DECODED_DIFF DECODED_SESSION; do
  assert_contains "echo \"\$$var\"" "API_TOKEN"
  assert_not_contains "echo \"\$$var\"" "s3cr3t-marker"
  assert_not_contains "echo \"\$$var\"" "plain-value-marker"
done

# the shell still gets the real value
assert_contains "echo \"$out\"" "s3cr3t-marker"

# a redacted value is never written to the env cache
assert "find '$MISE_STATE_DIR/env-cache' -type f 2>/dev/null | wc -l | tr -d ' '" "0"

# without a secret, the same config is cached as before
cat >"$MISE_CONFIG_DIR/config.toml" <<TOML
[env]
PLAIN_VAR = "plain-value-marker"
TOML
mise env -s bash >/dev/null
assert_directory_exists "$MISE_STATE_DIR/env-cache"
