#!/bin/bash

# If $1 param is empty defaults to vmx-nas
HOSTNAME=vmx-nas && [[ -n $1 ]] && HOSTNAME="$1"
# If $2 param is empty defaults to 10M
RCLONE_BW=10M && [[ -n $2 ]] && RCLONE_BW="$2"
RCLONE_ADDRESS=$HOSTNAME.swallow-grue.ts.net:44444
RCLONE_CRED=rcd
RCLONE_CONF_FILE=/opt/rclone/rclone.conf
RCLONE_SCRIPT_FILE=$(basename "$0") 
RCLONE_LOG_FILE="${RCLONE_SCRIPT_FILE%.*}.log"
[[ ! -f "$RCLONE_LOG_FILE" ]] && touch "$RCLONE_LOG_FILE"

CURRENT_TIME=$(date +%k%M)
#Returns the current rclone bandwidth and removes the double quotes pre/suffix
#rclone rc core/bwlimit returns rate in json form, jq '.rate' extract the rate value from json, sed -e 's/^"//' -e 's/"$//'` removes double quotes
CURRENT_BW=$(rclone rc --rc-addr="$RCLONE_ADDRESS" --rc-user=cartache --rc-pass=Cartache1X core/bwlimit | jq '.rate' | sed -e 's/^"//' -e 's/"$//')

#-------------------------
Day="2M"
Evening="1k"
BeforeMidnight="10M"
Night="15M"
#-------------------------

# echo "$CURRENT_TIME"

# #If override file is not present set bandwidth according to time else set it to 10K
# if [ $CURRENT_TIME -gt 2330 -a $CURRENT_TIME -le 2359 ]; then
#   BW=$BeforeMidnight
# elif [ $CURRENT_TIME -gt 001 -a $CURRENT_TIME -le 830 ]; then
#   BW=$Night
# elif [ $CURRENT_TIME -gt 1700 -a $CURRENT_TIME -le 2330 ]; then
#   BW=$Evening
# elif [ $CURRENT_TIME -gt 830 -a $CURRENT_TIME -le 1700 ]; then
#   BW=$Day
# fi

# echo "Current=$CURRENT_BW & New=$BW"

# if [[ $CURRENT_BW != $BW ]] ; then
# #	echo "$(date +%H:%M) - Bandwidth set to $BW"
# #	echo "$(date +%H:%M) - Bandwidth set to $BW" >> /mnt/user/Logs/BW.log
# 	rclone rc --rc-addr=192.168.10.18:5572 core/bwlimit --rc-user=cartache --rc-pass=Cartache1X rate=$BW
# #	echo "Current=$CURRENT_BW & New=$BW"
# fi

# daytime=$(date +%u%H)

# if [ "${daytime}" -ge  001 ] && [ "${daytime}" -le 830 ]
# then
#     echo "command for Friday after 18pm until Sunday 22pm"
# elif [ "${daytime}" -ge 318 ] && [ "${daytime}" -le 320 ]
# then
#     echo "command for Wednesday after 18pm until 20pm"
# else
#     echo "command for all other dates and times"
# fi

/usr/bin/rclone rc \
--config "$RCLONE_CONF_FILE" \
--rc-addr="$RCLONE_ADDRESS" \
--rc-user="$RCLONE_CRED" \
--rc-pass="$RCLONE_CRED" \
--log-file "$RCLONE_LOG_FILE" \
core/bwlimit rate="$RCLONE_BW"

# rclone rc --rc-addr=192.168.10.19:5572 core/bwlimit --rc-user=cartache --rc-pass=Cartache1X rate=$BW