# -*- shell-script -*-

make_dbus_udisks_call()
{
    local cmd=$1
    local field=$2
    local type=$3
    local object=$4
    local iface=$5
    local method=$6
    shift 6

    local ret=0
    local reply
    reply=$(busctl "${cmd}" --allow-interactive-authorization=false --expect-reply=true --json=short \
               org.freedesktop.UDisks2 "/org/freedesktop/UDisks2/${object}" \
               "org.freedesktop.UDisks2.${iface}" "${method}" "$@") || ret=$?

    if [[ $ret -ne 0 ]]; then
        echo "Error running ${cmd} ${method} on ${DEVICE} (status = $ret)" >&2
        exit 1
    fi

    # Expected reply must be of ${type} contain ${field}: value
    ret=$(jq -r "if .${field} != null and .type == \"${type}\" then .${field} else \"\" end" <<< "$reply" || true)
    if [[ -z $ret ]]; then
        echo "Error when running '${cmd} ${method}' on ${DEVICE}: udisks returned success but could not parse reply:" >&2
        echo "---"$'\n'"$reply"$'\n'"---" >&2
        exit 1
    fi

    # If we are returning an object strip the /org/freedesktop/UDisks2/ prefix
    if [[ $type = o ]]; then
        ret="${ret#/org/freedesktop/UDisks2/}"
    fi

    echo "$ret"
}

create_lock_file()
{
    local DEVBASE="$1"
    if [[ ! $DEVBASE =~ ^[a-z0-9]+$ ]]; then
        echo "Ignoring malformed device name /dev/${DEVBASE}" >&2
        return 1
    fi

    local MOUNT_LOCK="/var/run/jupiter-automount-${DEVBASE}.lock"
    exec 9<>"$MOUNT_LOCK"
    if ! flock -n 9; then
        echo "Failed to obtain lock for /dev/${DEVBASE}" >&2
        return 1
    fi
}
