#!/usr/bin/env bash
# Ordinary origin lifecycle, including stale plans and disconnected operation.
require_cmd git
export MISE_HISTORY_NOTIFY=false
origin="$PWD/origin.git"
git init -q --bare -b main "$origin"
echo base >~/.native
assert_succeed 'mise bootstrap dotfiles track ~/.native'
assert_fail 'mise bootstrap dotfiles sync' 'no setup repository'
assert_succeed "mise bootstrap dotfiles origin set file://$origin --sync manual --yes"
second="$(dirname "$HOME")/sync-b"
mkdir -p "$second"
b() {
  (
    cd "$second" || exit
    env HOME="$second" XDG_CONFIG_HOME="$second/.config" MISE_CONFIG_DIR="$second/.config/mise" \
      MISE_STATE_DIR="$second/.local/state/mise" MISE_DATA_DIR="$second/.local/share/mise" \
      MISE_CACHE_DIR="$second/.cache/mise" MISE_TRUSTED_CONFIG_PATHS="$second" mise "$@"
  )
}
export second
export -f b
assert_succeed "b bootstrap --from-git file://$origin --yes"
echo incoming >~/.native
assert_succeed 'mise bootstrap dotfiles sync'
assert_succeed 'b bootstrap dotfiles sync --fetch-only'
echo saved-after-plan >"$second/.native"
assert_succeed 'b bootstrap dotfiles save'
assert_fail 'b bootstrap dotfiles pull --yes' paused
assert "cat $second/.native" saved-after-plan
assert_succeed "b bootstrap dotfiles pull --keep-local $second/.native --yes"
assert_succeed 'b bootstrap dotfiles sync'
assert_succeed 'mise bootstrap dotfiles sync --fetch-only'
echo unsaved-after-plan >~/.native
assert_fail 'mise bootstrap dotfiles pull --yes' paused
assert 'cat ~/.native' unsaved-after-plan
assert_succeed "mise bootstrap dotfiles pull --take-remote $HOME/.native --yes"
assert 'cat ~/.native' saved-after-plan
head=$(git --git-dir="$origin" rev-parse main)
mv "$origin" "$origin.offline"
echo offline >~/.native
assert_succeed 'mise bootstrap dotfiles save'
assert_fail 'mise bootstrap dotfiles sync'
assert 'cat ~/.native' offline
mv "$origin.offline" "$origin"
assert_succeed 'mise bootstrap dotfiles sync'
assert_succeed "git --git-dir=$origin merge-base --is-ancestor $head main"
assert 'mise bootstrap dotfiles status --json | jq -r .history.sync.last_error' null
assert_succeed 'mise bootstrap dotfiles origin --remove'
assert_contains 'mise bootstrap dotfiles status' 'Setup repository: none'
assert_succeed 'mise bootstrap dotfiles save --description disconnected'
assert_fail 'mise bootstrap dotfiles sync'
