##
# systr_init_wktree <path>
#
# Assert that the repository exists, then setup the .systr directory
# at the CWD.
##
function systr_init_wktree
{
    if [ $# -lt 1 ]; then
        echo "Fatal: too few args to init_wktree" >&2
        exit 1
    fi

    path="$1"
    systr_repo_check "$path"

    mkdir .systr
    echo "$path" >.systr/path
    echo "NULL"  >.systr/BASE
    echo "NULL"  >.systr/TRAC
    date >.systr/updated

    echo "Setup worktree at $(pwd)"
}

##
# systrunk checkout <commit> [<path>]
#
# Reset a worktree to the state at <commit>.  If <path> is given,
# checkout also initializes a new worktree at the CWD.  While
# resetting to <commit>, all local uncommitted changes are lost.
#
# After checkout, BASE and TRAC will be set to <commit>.
##
function systr_checkout
{
    if [ $# -lt 1 ]; then
        echo "Fatal: too few arguments to systr_checkout" >&2
        exit 1
    fi

    version="$1"

    if [ $# -gt 1 ]; then
        systr_init_wktree "$2"
        read path <.systr/path
        read BASE <.systr/BASE
        read TRAC <.systr/TRAC
    fi

    if [[ "$version" == "NULL" ]]; then
        echo "Checking out NULL :: Checkout not performed"
        exit
    fi

    if [[ "$version" == "TRAC" ]]; then
        version="$TRAC"
    fi

    commit=$(systr_repo_resolve_reference "$version")
    echo "$commit" >.systr/BASE

    if [[ "$version" != "BASE" ]]; then
        echo "$version" >.systr/TRAC
    fi

    if [[ "$commit" == "NULL" ]]; then
        echo "Nothing to checkout"
        exit
    fi

    echo "Checking out files..."
    systr_rsync_normal "$path/revs/$commit/" .
}