#!/usr/bin/env bash

# A project .miserc.toml loads without trust, so it must not be able to drop an
# environment the global miserc selects, such as one that turns paranoid on.
export MISE_TRUSTED_CONFIG_PATHS=""
mkdir -p "$MISE_CONFIG_DIR/conf.d/floor"
echo 'env = ["floor"]' >"$MISE_CONFIG_DIR/miserc.toml"
cat >"$MISE_CONFIG_DIR/conf.d/floor/mise.floor.toml" <<'TOML'
[settings]
paranoid = true
TOML

mkdir project
cat >project/mise.toml <<'TOML'
[env]
FROM_PROJECT = "{{ exec(command='echo pwned') }}"
TOML
cat >project/mise.development.toml <<'TOML'
[settings]
paranoid = false
TOML
cd project || exit 1
assert "mise settings get paranoid" "true"

for file in .miserc.toml .miserc.local.toml .config/miserc.toml; do
  mkdir -p .config
  echo 'env = []' >"$file"
  assert "mise settings get paranoid" "true"
  assert_fail "CI=1 mise exec --yes -- printenv FROM_PROJECT" "not trusted"
  rm "$file"
done

# A parent directory's file cannot drop it either, nor can a template.
echo 'env = []' >../.miserc.toml
assert "mise settings get paranoid" "true"
rm ../.miserc.toml
echo '{% if os() %}env = []{% endif %}' >.miserc.toml
assert "mise settings get paranoid" "true"

# The project can still add its own environments, which paranoid mode makes
# trust before they load. One listed after the global environment, or listed
# with the global one moved last, cannot turn paranoid off.
for envs in '["development"]' '["development", "floor"]'; do
  echo "env = $envs" >.miserc.toml
  assert "mise settings get paranoid" "true"
  assert_fail "mise config ls" "mise.development.toml are not trusted"
done

# The user can still choose for themselves.
assert "MISE_ENV=other mise settings get paranoid" "false"
rm .miserc.toml

# Nor can a project's env_conf_d change how a global conf.d fragment loads.
# With env_conf_d on, security.floor.toml loads for the floor environment, above
# config.toml; off, it would load unconditionally, below config.toml.
rm -r "$MISE_CONFIG_DIR/conf.d/floor"
printf 'env = ["floor"]\nenv_conf_d = true\n' >"$MISE_CONFIG_DIR/miserc.toml"
cat >"$MISE_CONFIG_DIR/conf.d/security.floor.toml" <<'TOML'
[settings]
paranoid = true
TOML
cat >"$MISE_CONFIG_DIR/config.toml" <<'TOML'
[settings]
paranoid = false
TOML
assert "mise settings get paranoid" "true"
echo 'env_conf_d = false' >.miserc.toml
assert "mise settings get paranoid" "true"
assert "MISE_ENV_CONF_D=0 mise settings get paranoid" "false"
