#!/bin/bash
# Builds a real, read-only GVFS mount with an owned loopback DAV endpoint.
set -euo pipefail
. "$(dirname "$0")/flea-sandbox-guard"

# This tool reads machine output and launches no application for the user.
export LC_ALL=C.UTF-8
unset LANGUAGE

# DAV replaces the archive backend, which GVFS 1.62 removed; actions: make, uri, mount, unmount, clean.
dir=${DIR:-$FIXTURE_ROOT/flea-gvfs-fixture}
helper="$(dirname "$0")/flea-gvfs-dav.py"
fail() { printf 'flea-gvfs-fixture: %s\n' "$*" >&2; exit 1; }

sandbox_require "$dir"
dir=$SANDBOX_PATH
command -v gio >/dev/null || fail "no gio on PATH"
command -v python3 >/dev/null || fail "no python3 on PATH"

unmount_fixture() {
    [ -f "$dir/uri" ] || return 0
    local uri mounts
    uri=$(python3 "$helper" uri "$dir")
    mounts=$(gio mount -l) || fail "could not list mounts"
    # Sample input: Mount(0): share.zip on 127.0.0.1 -> dav://127.0.0.1:2222/share.zip
    if printf '%s\n' "$mounts" | sed -n 's/^Mount([0-9]*): .* -> //p' | sed 's:/$::' | grep -Fx -- "${uri%/}" >/dev/null; then
        gio mount -u "$uri" || fail "could not unmount $uri"
    fi
}

case "${1:-make}" in
    make)
        if [ -e "$dir" ]; then
            sandbox_owned "$dir" || fail "fixture directory is not owned: $dir"
            unmount_fixture
            python3 "$helper" stop "$dir"
        fi
        sandbox_make "$dir"
        chmod 700 "$dir"
        mkdir "$dir/src"
        printf 'alpha\n' > "$dir/src/alpha.txt"
        printf 'beta\n' > "$dir/src/beta.txt"
        python3 "$helper" start "$dir"
        ;;
    uri|mount|unmount|clean)
        if [ ! -d "$dir" ]; then
            case "$1" in clean|unmount) exit 0 ;; esac
            fail "no fixture at $dir, run make first"
        fi
        sandbox_owned "$dir" || fail "fixture directory is not owned: $dir"
        case "$1" in
            uri) python3 "$helper" uri "$dir" ;;
            mount)
                uri=$(python3 "$helper" uri "$dir")
                gio mount "$uri" || fail "could not mount $uri"
                ;;
            unmount) unmount_fixture ;;
            clean)
                unmount_fixture
                python3 "$helper" stop "$dir"
                sandbox_remove "$dir"
                ;;
        esac
        ;;
    *) fail "unknown action '$1', expected make, uri, mount, unmount or clean" ;;
esac
