#!/bin/bash
#/###################################################################\
#| Download backup's from backup.castanedo.es                        |
#| Download a complete directory in a ssh server (sftp protocol).    |
#| Help:                                                             |
#|   -$host: host name or IP of the remote server.                   |
#|    Ex: backup.example.com                                         |
#|   -$sftpuser: user for SFTP.                                      |
#|   -$sftppass: password for SFTP.                                  |
#|   -$sftpkey: keyfile for SFTP (if is set $sftppass will be the    |
#|     key password).                                                |
#|   -$backupDir: directory to save repository files.                |
#| Warning:                                                          |
#|    Store passwords in bash scripts is very unsecure.              |
#|    (Contributions with keyrings are welcome).                     |
#|                                                                   |
#| Guzmán Castanedo (guzman@castanedo.es)                            |
#| January 2018                                                      |
#| Licence: GPL v3.0 -> https://www.gnu.org/licenses/gpl-3.0.en.html |
#\###################################################################/

host="backup.castanedo.es"
sftpuser="sftpuser"
sftppass="sftppass"
sftpkey="" #Not set key file -> Normal Password Auth
#sftpkey=/home/$USER/.ssh/your.key
remotefile=/var/www/*.html
backupDir=/home/$USER/Documentos/backup

#Check dependencies
if [ ! -x $(which ssh) ];then
	printf "ERROR:\tssh client Not Installed :O"
	exit 1
fi
if [ ! -x $(which sshpass) ];then
	printf "ERROR:\tsshpass Not Installed :O\n"
	exit 1
fi

#Check directory and create it
if [ ! -d $backupDir/$host ];then
	mkdir -p $backupDir/$host
	if [ $? != 0 ];then
		printf "ERROR: Imposible crear %s\n" $backupDir/$host
		exit 1
	fi
fi

#Download with sftp
printf "Destino backups:\t%s\n" $backupDir/$host
cd $backupDir/$host
echo "Sincronizando backup's desde sftp://$sftpuser@$host:$remotefile"
if [ ! -f $sftpkey ] || [ -z $sftpkey ];then
	#Use Normal Password Auth
	export SSHPASS=$sftppass
	sshpass -e sftp -oBatchMode=no -a $sftpuser@$host:$remotefile
	if [ $? != 0 ];then
		printf "ERROR:\tSe han producido errores en la sincronizacion\n"
		exit 1
	fi
else
	#Use Private Key File
	export SSHPASS=$sftppass
	sshpass -e sftp -oBatchMode=no -a -i $sftpkey $sftpuser@$host:$remotefile
	if [ $? != 0 ];then
		printf "ERROR:\tSe han producido errores en la sincronizacion\n"
		exit 1
	fi
fi
printf "Descarga correcta :)\n"