#!/bin/bash
# Sync selected files from Thunar to a remote server
selection="$*"
options=-avzs
# -a required for creating directory on remote side if none exists
# -v Nice to have for showing output
# -z Compress files
# -s required for remote directories that might have a space in their name
function rsync_func () {
        if [[ -z "$servers" ]]; then
                echo "No servers selected. Exiting..."
                exit 0
        else
                destination_total=$(echo "$servers" | wc -w)
                destination_count=1
                while [ "$destination_count" -le "$destination_total" ]
                do
                        server_list_select=$(printf "$server_list" | sed "$destination_count!d")
                        destination=$(printf "$destination_list" | sed "$server_list_select!d" | cut -d"'" -f2)
                        rlocation=$(printf "$rlocation_list" | sed "$server_list_select!d" | cut -d"'" -f2)
                        args=$(printf "rsync --progress $options $selection $destination:$rlocation")
                        eval "$args"
                        error_check
                        ((destination_count++))
                done
                read -s -n 1 -p "Press any key to exit..."
        fi
}
function read_config () {
        destination_list=$(cat ~/.config/rsync-client/client.conf | sed '/^\s*$/d' | grep -v "#" | cut -d" " -f1 | grep -n "" | sed "s/:/ '/g; s/$/' off/g")
        rlocation_list=$(cat ~/.config/rsync-client/client.conf | sed '/^\s*$/d' | grep -v "#" | cut -d" " -f2- | grep -n "" | sed "s/:/ '/g; s/$/'/g")
}
function select_server () {
        if [[ -z "$destination_list" ]]; then
                echo "No servers available from config file. Exiting..."
                read -s -n 1 -p "Press any key to exit..."
                exit 0
        else
                servers=$(dialog --stdout --checklist "Select:" 0 0 0 $destination_list)
                server_list=$(echo $servers | sed 's/ /\n/g')
                clear
       fi
}
function error_check () {
        if [ $? -eq 0 ];
        then
                echo "rsync to $destination complete!"
        else
                echo "Rsync encountered an error for $destination"
                notify-send "Rsync encountered an error for $destination"
                while true;
                do
                        read -p "Do you wish to continue? y/n " prompt
                        case $prompt in
                                y|Y ) break;;
                                n|N ) exit;;
                                * ) echo "Please select an option.";;
                        esac
                done
        fi
}
read_config
select_server
rsync_func
