#!/usr/bin/env bash
require_cmd git
export MISE_EXPERIMENTAL=0
printf 'original\n' >~/.onboard-review
assert_succeed 'mise bootstrap dotfiles track ~/.onboard-review'
assert_succeed 'mise bootstrap dotfiles track ~/.config/mise/config.toml'
origin="$PWD/origin.git"
git init -q --bare -b main "$origin"
assert_succeed "mise bootstrap dotfiles origin set file://$origin --sync fetch-only --yes"
assert 'mise settings get history.sync' 'fetch-only'
assert_succeed 'mise settings set history.sync manual'
assert 'mise settings get history.sync' 'manual'
assert_contains 'mise bootstrap dotfiles status' 'mode manual'
assert_succeed 'mise settings set history.sync sync'
assert 'mise settings get history.sync' 'sync'
assert_succeed 'mise settings unset history.sync'
assert 'mise settings get history.sync' 'sync'
assert_succeed 'mise bootstrap dotfiles sync'

# A broken local store must not turn a marked repository into a plain clone.
broken="$PWD/broken-state"
mkdir -p "$broken/history"
printf 'not a repository\n' >"$broken/history/repo.git"
assert_fail "MISE_STATE_DIR=$broken mise bootstrap --from-git file://$origin --yes" 'history is unavailable'
assert_fail 'test -d ~/.config/mise/.git'

# Preview and refusal cannot alter an existing connection's bookkeeping.
status="$MISE_STATE_DIR/history/sync.json"
cp "$status" "$PWD/sync-before.json"
refs="$(git --git-dir="$MISE_STATE_DIR/history/repo.git" for-each-ref --format='%(refname) %(objectname)')"
assert_succeed "mise bootstrap --from-git file://$origin --dry-run --only dotfiles"
assert_succeed "cmp '$status' '$PWD/sync-before.json'"
assert "git --git-dir=$MISE_STATE_DIR/history/repo.git for-each-ref --format='%(refname) %(objectname)'" "$refs"
assert_fail "MISE_YES=0 mise bootstrap --from-git file://$origin --only dotfiles </dev/null" 'not set up'
assert_succeed "cmp '$status' '$PWD/sync-before.json'"
assert "git --git-dir=$MISE_STATE_DIR/history/repo.git for-each-ref --format='%(refname) %(objectname)'" "$refs"

# A validation failure after fetching also leaves the old state untouched.
git clone -q "$origin" damaged
printf '[broken\n' >damaged/config/config.toml
git -C damaged add config/config.toml
git -C damaged -c user.name=test -c user.email=test@example.com commit -qm invalid
git -C damaged push -q
assert_fail "mise bootstrap --from-git file://$origin --dry-run --only dotfiles"
assert_succeed "cmp '$status' '$PWD/sync-before.json'"
assert "git --git-dir=$MISE_STATE_DIR/history/repo.git for-each-ref --format='%(refname) %(objectname)'" "$refs"
