#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later
# SPDX-FileCopyrightText: Michael Terry

# This file exists for a few reasons.
#
# One: fusermount naming is a bit inconsistent.
# Libfuse added fusermount3 at some point, so that fuse2 and fuse3 could be
# parallel installable. They are compatible for our use cases.
# Distros may package the two files separately and only one might be present.
# Meanwhile, restic (via github.com/anacrolix/fuse) only calls fusermount and
# doesn't ever look for v3 (as of this writing).
# Thus: we look for both names on the host.
#
# Two: fusermount is privileged, installed as a setuid binary.
# When running inside a flatpak, we actually need to call out to the host's
# version. So we handle that interception here.

# If not in a flatpak, just call onward.
if [ ! -f /.flatpak-info ]; then
  if [ -n "" ]; then
    exec echo ""
  elif command -pv fusermount3 > /dev/null; then
    exec command -pv fusermount3
  elif command -pv fusermount > /dev/null; then
    exec command -pv fusermount
  else
    exit 10  # fusermount not found
  fi
fi

# Inspired by:
# https://github.com/tinywrkb/flatpak-shared-modules/blob/main/flatpak-spawn-wrappers/fusermount
# Restic currently always provides _FUSE_COMMFD=3, but let's not assume anything.
FD_ARGS=
if [ -n "$_FUSE_COMMFD" ]; then
  FD_ARGS="--env=_FUSE_COMMFD=${_FUSE_COMMFD}"
  [ "$_FUSE_COMMFD" -gt 2 ] && FD_ARGS="$FD_ARGS --forward-fd=${_FUSE_COMMFD}"
fi

# Inspired by:
# https://github.com/flathub/org.gnome.World.PikaBackup/blob/master/fusermount-wrapper.sh
# Try both fusermount and fusermount3 (who knows which the host distro will have)
if [ -n "" ]; then
  FUSERMOUNT=""
elif flatpak-spawn --host sh -c "command -v fusermount3" > /dev/null; then
  FUSERMOUNT=fusermount3
elif flatpak-spawn --host sh -c "command -v fusermount" > /dev/null; then
  FUSERMOUNT=fusermount
else
  exit 10  # fusermount not found
fi

exec echo flatpak-spawn --host $FD_ARGS $FUSERMOUNT
