#! /bin/sh -
#
# Load the fuse module (if exists) and mount the fuse control file system
#
# Copyright (c) 2019-2020 Matias Fonzo, <selk@dragora.org>.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

PROGRAM="${0##*/}"

# Sanity check
if ! command -v fusermount > /dev/null
then
    echo "${0}: Error: fusermount(1) is not available." 1>&2
    exit 127;
fi

# Main functions

fuse_start()
{
    if modinfo fuse > /dev/null 2>&1
    then
        echo "${PROGRAM}: Loading fuse (kernel) module ..."
        modprobe fuse
    fi

    if ! mountpoint -q /sys/fs/fuse/connections
    then
        echo "${PROGRAM}: Mounting fusectl filesystem ..."
        mount -v -t fusectl fusectl /sys/fs/fuse/connections
    else
        echo "${PROGRAM}: FUSE filesystem already mounted at /sys/fs/fuse/connections" 1>&2
    fi
}

fuse_stop()
{
    if mountpoint -q /sys/fs/fuse/connections
    then
        echo "${PROGRAM}: Unmounting FUSE filesystem ..."
        umount -v /sys/fs/fuse/connections
    else
        echo "${PROGRAM}: FUSE filesystem not mounted." 1>&2
    fi

    if grep -q -w ^fuse /proc/modules
    then
        echo "${PROGRAM}: Unloading fuse (kernel) module ..."
        rmmod fuse
    fi
}

# Command line arguments

case $1 in
start)
    fuse_start
    ;;
stop)
    fuse_stop
    ;;
restart)
    fuse_stop
    fuse_start
    ;;
*)
    echo "Usage: $0 (start|stop|restart)" 1>&2
    exit 1
    ;;
esac

