print all conflicts in the current channel
#!/bin/bash
set -euo pipefail

PIJUL_CONFLICTS="${PWD}/target/debug/pijul-conflicts"

# set up a repo with a default channel named "alice", and another channel "bob"
initrepo() {
    local repo=$(mktemp -d -q)
    pijul init "${repo}" --channel alice 2> /dev/null
    pijul fork bob --repository "${repo}"
    echo "${repo}"
}

pijul_rec() {
    local hash="$(pijul record --all --message "${1}")"
    echo -n "${hash:6}"
}

newfile() {
    local file="$1"
    pijul channel switch alice &> /dev/null
    cat <<EOF > ${file}
A
B
C
EOF
    pijul add ${file} 2> /dev/null
    local hash="$(pijul_rec "add ${file}")"
    pijul channel switch bob &> /dev/null
    pijul apply "${hash}" &> /dev/null
    pijul reset 2> /dev/null
}

cleanup() {
    rm -rf "${1}"
}

runtest() {
    local repo="${1}"
    local test="${2}"

    echo ">>> test: ${test} in repo ${PWD}"

    "${test}"
}

# Some utilities
pijul_switch() {
    #pijul fork "${1}"
    pijul channel switch "${1}" &> /dev/null
}

# Alice and Bob modify the same line in the same file
order_conflict() {
    newfile file.txt
    sed -i -e 's/B/X/g' file.txt
    hash="$(pijul_rec "bobdor")"

    pijul channel switch alice &> /dev/null
    sed -i -e 's/B/Y/g' file.txt
    pijul_rec "alice wuz here" > /dev/null

    pijul apply "${hash}" &> /dev/null
}

# Showcase a zombie line conflict - Bob inserts a line above a line
# that Alice removes
zombies() {
    newfile file2.txt
    sed -i -e 's/B/X\nB/g' file2.txt
    local hash="$(pijul_rec "bob does stuff")"

    pijul channel switch alice &> /dev/null
    sed -i -e '/B/d' file2.txt
    pijul_rec "alice deletes" > /dev/null
    pijul apply "${hash}" &> /dev/null
}

TESTS=(
    "order_conflict"
    "zombies"
)

repo="$(initrepo)"
pushd "${repo}" > /dev/null
for t in "${TESTS[@]}"; do
    runtest "${repo}" "${t}"
done


"${PIJUL_CONFLICTS}"
popd > /dev/null

cleanup "${repo}"