#!/bin/bash

# Simple PoC of NUT client as a FUSE mountable filesystem
# Requires https://github.com/vi/execfuse
# Copyright (C) 2024 by Jim Klimov <jimklimov+nut@gmail.com>
# Licensed GPLv2+ as NUT codebase

if [ x"$NUT_DEBUG_FUSE" = xtrue ] ; then
    exec 2>"/tmp/nut-debug-fuse-`basename $0`.log"
    echo "ARGS($#, $0): 1='$1' 2='$2' @='$@'" >&2
fi

D=""
F=""
case "$1" in
    /|/by-server)
        D="$1"
        ;;
    /by-server/*/*/*/*) # Don't want subdirs here
        ;;
    /by-server/*/*/*)
        # VARNAME
        F="`basename "$1"`"
        # UPSSRV/UPSNAME
        D="`echo "$1" | sed 's,^/by-server/\(.*\)/'"$F"'$,\1,'`"
        ;;
    /by-server/*/*)
        # UPSSRV/UPSNAME
        D="`echo "$1" | sed 's,^/by-server/\(.*\)$,\1,'`"
        ;;
    /by-server/*) # No further slash
        # UPSSRV
        D="`basename "$1"`"
        ;;
    /client-location|/client-version)
        F="$1"
        ;;
    *)
        ;;
esac

if [ -n "$F" ] ; then
    printf 'ino=1 mode=-r--r--r-- nlink=1 uid=0 gid=0 rdev=0 size=0 blksize=512 blocks=2 atime=0 mtime=0 ctime=0 %s\0' "$1"
else
    if [ -n "$D" ] ; then
        printf 'ino=1 mode=drwxr-xr-x nlink=16 uid=0 gid=0 rdev=0 size=4096 blksize=512 blocks=2 atime=0 mtime=0 ctime=0 %s\0' "$1"
    else
        exit 1
    fi
fi

