#!/bin/bash
# Rclone "remote" drive mounter script v0.9 , GPL licence, by PPC, 19/6/2020, revised 19/7/2023
#Allows to automatically configure GoogleDrive and OneDrive, in rclone, or to manually configure (almost) any Cloud Service, and then mount it and access it in the default File Manager
##############
TEXTDOMAINDIR=/usr/share/locale
TEXTDOMAIN=access-cloud

#### Check for dependencies, clear files, set variables ####
#Check for needed utilities:
## testing for  yad
	if ! [ -x "$(command -v yad)" ]; then
  	 x-terminal-emulator -e whiptail --title "Warning" --msgbox "You need to have YAD installed." 8 78
     exit 1
    fi
    
## Test for "rclone" dependency and try to install it, if user so selects
if ! [ -x "$(command -v rclone)" ]; then
	yad --title=$"antiX Cloud" --window-icon=/usr/share/icons/papirus-antix/48x48/places/folder-red-meocloud.png --center --text="\n  Download rclone (~ 60Mb)? \n" --button=" OK ":1 --button=" x ":2
	 foo=$?
	 #This next line zeroes the file that is used to flag the end of the install process (in the end of the follwoing if statement, the "; echo 1 > /tmp/finished1" part changes that's file's content, signaling that the process is over and the main script can continue running:
	 echo 0 > /tmp/finished1
	 
	if [[ $foo -eq 2 ]]; then exit
	fi
	 
	if [[ $foo -eq 1 ]]; then x-terminal-emulator -e /bin/bash -c "gksu 'apt update' && gksu 'apt install -y rclone'; echo 1 > /tmp/finished1"
	fi
	 #wait until install process is finished (this waits until the "sudo apt install" process running in paralel echoes the value 1 to the /tmp/finished1 file:
   finished=$(cat /tmp/finished1)
	until [ $finished -gt 0 ]	
	do
	finished=$(cat /tmp/finished1)
	done
fi
	
#Clear log file(s), export function(s), set global variables:
rm /tmp/rclone_remote_list.txt
#IF no config file for the tray icon exists, create one and set to show tray by default:
if [ ! -f /tmp/rclone_tray.txt ]; then
    echo "rclone_tray.txt not found!"
    tray_default="TRUE|"
    echo $tray_default > /tmp/rclone_tray.txt
fi
# Generate log file with configured "remote" cloud drives and check if log file is empty, if so,  present user with option to configure a new cloud "remote" drive
rclone listremotes > /tmp/rclone_remote_list.txt
log_file="/tmp/rclone_remote_list.txt"
[ -s $log_file ] || Manage_remotes


Help(){
# show Help screen
yad --title=$"antiX Cloud - Help" --window-icon=/usr/share/icons/papirus-antix/48x48/places/folder-red-meocloud.png --center --width=450 --height=550  --fixed --text=$"\n What is this: \n This application makes many Cloud storage devices, like Google Drive, Ms One Drive, etc, accessible from your default File Manager, just like they were a network drive or a thumb-drive. \n  This is simply a Graphics User Interface for rclone, that is used to mount those services. \n \n What this is not:\n This is not a way to sync a folder with any cloud service, so, if you don't have access to the Internet, you have no local copy of any file stored on the cloud (unless you previously downloaded it to your computer).\n \n Notes:\n -To view the contents of some cloud drives, like OneDrive, you may need to refresh your File Manager.\n -When the user starts a 'remote' cloud drive, a tray icon is launched, to provide easy access to the main menu. This tray icon only closes when the 'Quit' button is pressed. \n \n How to configure your cloud storage service:\n 1- When you launch this application for the first time you are shown the 'Manage' menu, that allows you to try to automaticaly configure your Google Drive Account. \n If you click the 'Google Drive' Button, your internet browser opens on your cloud account service. You have to log on and autorise 'rclone' access to your account. After the config process is done, if you don't want to configure more services, click the 'Quit' button and the main Window pops up. From there you can double left click your Cloud account name, to access it's contents. \n At any time, in the main window, if you click the 'Manage drives' button, will will be presented with the initial configuration menu. \n 2- Manually configuring cloud storage services: \n if you click the 'Manage' button, a terminal will pop open. You have to use the keyboard to perform your selections. After you finished seting up your cloud service, press 'q' from the main terminal menu to exit. Restart this application to access the 'remote' drives you just configured. \n \n SECURITY WARNING: \n Do not use this application on a shared computer, because this provides access to your cloud accounts without any need of entering a password!!!" --button=$"On line help":'desktop-defaults-run -b rclone.org/drive/' --button=$"Close":1	
} # end of 'Help' function

Manage_remotes(){
	export -f Help Main_window
	
	# Manage "remotes" or automaticaly add a Google Drive or MS OneDrive personal account- this automaticaly pops up if no "remote" cloud drives are configured
	yad --title=$"antiX Cloud - Configuration" --window-icon=/usr/share/icons/papirus-antix/48x48/places/folder-red-meocloud.png --center --button=$"Google Drive!/usr/share/icons/papirus-antix/48x48/categories/googledrive.png!Automatically add Google Drive access":2 --button=$"OneDrive!/usr/share/icons/papirus-antix/48x48/categories/goa-account-exchange.png!Automatically add OneDrive access":3 --button=$"Manage Cloud Drives!/usr/share/icons/papirus-antix/48x48/categories/steam_icon_427520.png!Manually manage Cloud 'remote' drives, using a Terminal interface":'desktop-defaults-run -t rclone config' --button=$"Manage Tray icon!!Select if a tray icon should be displayed while cloud drives are used":4 
	
	 foo=$?
	 
	 	if [[ $foo -eq 2 ]]; then
			#automatically configure  GoogleDrive in rclone - may break at any time
			touch ~/.config/rclone/rclone.conf
			echo >> ~/.config/rclone/rclone.conf [GoogleDrive]
			echo >> ~/.config/rclone/rclone.conf type = drive
			echo >> ~/.config/rclone/rclone.conf team_drive =
			rclone config update GoogleDrive drive config_is_local=false
			#restart the program:
			$(basename $0) && exit
		fi
		
		if [[ $foo -eq 3 ]]; then
		    #automatically configure OneDrive in rclone - may break at any time
	 		touch ~/.config/rclone/rclone.conf
			echo >> ~/.config/rclone/rclone.conf [OneDrive]
			echo >> ~/.config/rclone/rclone.conf type = onedrive
			echo >> ~/.config/rclone/rclone.conf team_drive =
			rclone config update OneDrive drive config_is_local=false
			#restart the program:
			$(basename $0) && exit
		fi
	 
		if [[ $foo -eq 4 ]]; then
			tray=$(yad  --title=$"antiX Cloud" --window-icon=/usr/share/icons/papirus-antix/48x48/places/folder-red-meocloud.png --form --center --field 'Use Tray icon - NOTE: Requires restart!':chk true) && echo $tray > /tmp/rclone_tray.txt
			#restart the program:
			$(basename $0) && exit
		fi
		
	Main_window
	
	} #end of 'Manage_remotes' funtion
	
Main_window(){
### Main Window ####
### export functions, set variables:
export -f Help Manage_remotes Main_window
now=`date +"%Y-%m-%d"`
# Choose an existing "remote" cloud service using yad (or unmount or manage "remotes")
 rclone listremotes > /tmp/rclone_remote_list.txt
 log_file="/tmp/rclone_remote_list.txt"
 selection=$(yad --title=$"antiX Cloud" --window-icon=/usr/share/icons/papirus-antix/48x48/places/folder-red-meocloud.png --width=550 --height=400 --center --separator=" " --list  --column=$" Double click the 'remote' Cloud service that you want to access "  --button=$"Unmount Drives!/usr/share/icons/papirus-antix/24x24/devices/drive-removable-media.png!Unmounts all 'remote' cloud drives":1 --button=$"Configuration!/usr/share/icons/papirus-antix/48x48/actions/configuration.png!Allows to manage cloud drives and the tray icon":2 --button=$"Help!/usr/share/icons/papirus-antix/24x24/categories/xfce-unknown.png!":"bash -c Help" --button=$" x !!Closes the application and its tray icon":3 < /tmp/rclone_remote_list.txt)
 foo=$?

if [[ $foo -eq 3 ]]; then
	pkill yad
	exit 1
fi

if [[ $foo -eq 2 ]]; then
	Manage_remotes
fi

if [[ $foo -eq 1 ]]; then
	# unmount all "remote" cloud drives
	pkill rclone
    # Try to delete empty mountpoint directories listed in log file:
file=~/.config/rclone/mountpoint_list.conf
lines=`cat $file`
for line in $lines; do
printf "\n**Trying to remove moint point: ${line} **\n\n"
eval fusermount -u ~/"${line}"
eval rmdir ~/"${line}"
done
	# Delete log file
	rm $file	
	Main_window
fi

####This avoids errors, if no selection was made:
if [ -z "$selection" ]; then
		exit 1
fi

#### Mount and show "remote" cloud drive:
# create a mount point using the same name as the remote, without spaces, AND CURRENT DATE to avoid problems:
mount_point=$(echo $selection | sed 's/.$//')
mount_point_no_spaces=$(echo $mount_point | sed -e 's/ //g')
mount_point_no_spaces=$mount_point_no_spaces-antiX
mkdir ~/$mount_point_no_spaces
# add name of directory to a config file, to be able to, when unmounting, also delete the empty mount point folder
( echo $mount_point_no_spaces ; echo "" ) >> ~/.config/rclone/mountpoint_list.conf
# mount the cloud service
comma="'"
and="&"
myVar=$(echo "rclone --vfs-cache-mode writes mount "${comma}""${selection}"${comma}")
myVar2=`echo $myVar | sed -E 's/.(.)$/\1/'`
eval "nohup  $myVar2 ~/$mount_point_no_spaces $and"
#echo  Running mount command: $myVar2 ~/$mount_point_no_spaces
#show the cloud service contents on the default file manager: for other distros other than antiX, that have xdg-open installed uncoment the following line and comment the "desktop-defaults" one...
 #xdg-open "~\$mount_point_no_spaces"  
sleep 2 &&
##desktop-defaults-run -fm ~/$mount_point_no_spaces
zzzfm ~/$mount_point_no_spaces
} #end of 'Main_window' funtion

export -f Help Manage_remotes Main_window

#If no Cloud drives are configured, automaticly launch the "Manage_remotes" window (this is done by using "rclone listremotes" to create a file listing all configured Cloud drives and saving that to a temporary file. Then check that file, if it's empty, there are no remotes, so launch "Manage_remotes"
rclone listremotes > /tmp/rclone_remote_list.txt
[ -s /tmp/rclone_remote_list.txt ] && echo "Config file has content" || Manage_remotes

#Start Main window:
Main_window

#Show traybar icon (if user checked the Tray checkbox, in the main window, on by default): (the pkill yad garantees that there are no multiple instances of the icon on the toolbar, unfortunatly, also closes any other running yad window (TO-DO: find another way to avoid multiple instances) 
tray="TRUE|"
if grep -Fxq $tray /tmp/rclone_tray.txt ;then
    pkill yad
yad --notification --image="/usr/share/icons/papirus-antix/48x48/places/folder-red-meocloud.png" --command="bash -c Main_window" --text=$"Left click: Access Cloud Storage (Middle click: exits)"
else
cat /tmp/rclone_tray.txt
#    exit 1
fi
