#!/bin/bash

SRCNAMES="appdata Backup Cloud Ebooks isos Logs Movies Photos scripts Series Software Public"
MNTUSER="/mnt/user"
LOGDIR="$MNTUSER/Logs"
LOG="$LOGDIR/mergerfs.log"
checkOK="true"
	
# some helpers and error handling:
info() { printf "\n%s %s\n\n" "$( date )" "$*" >&2; }
trap 'echo $( date ) Mount interrupted >&2; exit 2' INT TERM

##
## Output to a logfile
##
#exec > >(tee -i $LOG)
#exec 2>&1

for SRCNAME in $SRCNAMES
do
	MOUNTPOINT="$MNTUSER/Union/$SRCNAME"
	TESTREMOTEFILE="$MOUNTPOINT/.mgfsrem_chk"
	if $SRCNAME == "Cloud" 
	then
		LOCALDIR="$MNTUSER/Cloud/gdrive"
		REMOTEDIR="$MNTUSER/Cloud/tdrive"
		TESTLOCALFILE=$TESTREMOTEFILE
	else
		LOCALDIR="$MNTUSER/$SRCNAME"
		if [ $SRCNAME == "Series" ]; then 
			REMOTENAME="tv"
		elif [ $SRCNAME == "Series_fr" ]; then 
			REMOTENAME="tv_fr"
		else
			REMOTENAME="${SRCNAME,}" #first letter in lowercase	
		fi
		REMOTEDIR="$MNTUSER/Cloud/tdrive/$REMOTENAME"
		TESTLOCALFILE="$MOUNTPOINT/.mgfsloc_chk"
	fi
	if [ ! -e "$TESTLOCALFILE" ] &&  [ ! -e "$TESTREMOTEFILE" ] ; then
		echo "$( date ) - Merging folders $LOCALDIR:$REMOTEDIR - mergerfs -o rw,async_read=false,use_ino,allow_other,func.getattr=newest,category.action=all,category.create=ff,cache.files=partial,dropcacheonclose=true $LOCALDIR:$REMOTEDIR $MOUNTPOINT" >> /mnt/user/Logs/mergerfs.log
		checkOK="false"
		fusermount -uz "$MOUNTPOINT"
		mergerfs -o rw,async_read=false,use_ino,allow_other,func.getattr=newest,category.action=all,category.create=ff,cache.files=partial,dropcacheonclose=true "$LOCALDIR":"$REMOTEDIR" "$MOUNTPOINT"
	fi
done

if [ $checkOK == "false" ]
then 
	echo "$( date ) - Remerging has been processed"  >> /mnt/user/Logs/mergerfs.log 
fi

