#!/bin/bash
# SPDX-License-Identifier: GPL-2.0
# Copyright (C) 2023 JELOS (https://github.com/JustEnoughLinuxOS)

CONFIGPATH="/storage/.config"

if [ -z "$2" ]
then
  if [ -e "${CONFIGPATH}/rsync.conf" ]
  then
    source ${CONFIGPATH}/rsync.conf
  else
    MOUNTPATH="/storage/cloud"
    SYNCPATH="GAMES"
  fi
else
  MOUNTPATH=${2}
fi

for CONFIG in rsync.conf rsync-rules.conf 
do
  if [ ! -e "${CONFIGPATH}/${CONFIG}" ]
  then
    cp -rf /usr/config/${CONFIG} ${CONFIGPATH}/${CONFIG}
  fi
done

function checkconfig() {
  if [ ! -e "${CONFIGPATH}/rclone/rclone.conf" ]
  then
    echo "You must configure rclone before using this tool.  Run \`rclone config\` to get started."
    exit 1
  fi
  if [ ! -d "${MOUNTPATH}" ]
  then
    mkdir -p ${MOUNTPATH}
  fi
}

function mount() {
  TARGET=$(rclone listremotes | awk '{printf $1; exit}')
  rclone mount ${TARGET}/ ${1} \
    --vfs-cache-mode writes \
    --vfs-cache-max-size 100M \
    --vfs-read-chunk-size-limit 128M \
    --vfs-read-chunk-size-limit off \
    --allow-non-empty \
    --dir-cache-time 48h \
    --log-file /var/log/rclone.log \
    --daemon
}

function unmount() {
  fusermount -u ${1}
}

case "${1}" in
  "mount")
    checkconfig
    mount ${MOUNTPATH}
  ;;
  "unmount")
    checkconfig
    unmount ${MOUNTPATH}
  ;;
  "$*")
    cat <<EOF
rclonectl is a simple rclone wrapper for mounting and unmounting cloud volumes using fuse.

Usage: rclonectl {mount,unmount} {path}

If no path is provided the tool will default to ${MOUNTPATH}.
EOF
   exit 0
  ;;
esac
