#!/usr/bin/env bash
# History filters use the same portable paths as checkpoints when HOME is a link.
require_cmd git
require_cmd jq
canonical_home="$HOME"
ln -s "$canonical_home" "$TMPDIR/home-alias"
export HOME="$TMPDIR/home-alias"
echo one >"$HOME/history-file"
ln -s history-file "$HOME/history-link"
assert_succeed "mise bootstrap dotfiles track '$HOME/history-file' '$HOME/history-link'"
for name in history-file history-link; do
  assert "mise bootstrap dotfiles history ls --path '$HOME/$name' --json | jq length" 1
  assert_succeed "mise bootstrap dotfiles history show latest --path '$canonical_home/$name' --json"
  assert_succeed "mise bootstrap dotfiles history diff --path '~/$name' --exit-code"
done
echo two >"$HOME/history-file"
assert_fail "mise bootstrap dotfiles history diff --path '$HOME/history-file' --exit-code"
assert_succeed "mise bootstrap dotfiles history diff --path '$HOME/history-link' --exit-code"

# rollback names the checkpoint that saved the version it restores, even
# when an unrelated later checkpoint holds it and HOME is a link
assert_succeed "mise bootstrap dotfiles save"
saved="$(mise bootstrap dotfiles history ls --path "$HOME/history-file" --json | jq -r '.[0].id')"
echo other >"$HOME/history-other"
assert_succeed "mise bootstrap dotfiles track '$HOME/history-other'"
echo three >"$HOME/history-file"
assert_contains "mise bootstrap dotfiles rollback '$HOME/history-file' --yes 2>&1" "rolled back ~/history-file to checkpoint $saved;"
assert "cat '$HOME/history-file'" two
