#!/bin/bash
#/###################################################################\
#| Download backup's from backup.castanedo.es                        |
#| Download all files in a http/https repository with Auth Basic     |
#| authentication.                                                   |
#| Help:                                                             |
#|   -$scheme: protocol (http, https, ftp, ...)                      |
#|   -$url: url without $scheme of the repository.                   |
#|    Ex: backup.example.com/some/where                              |
#|   -$httpuser: user for Auth Basic Auth.                           |
#|   -$httppass: password for Auth Basic Auth.                       |
#|   -$backupDir: directory to save repository files.                |
#|                                                                   |
#| Guzmán Castanedo (guzman@castanedo.es)                            |
#| March 2017                                                        |
#| Licence: GPL v3.0 -> https://www.gnu.org/licenses/gpl-3.0.en.html |
#\###################################################################/

scheme="https://"
url="backup.castanedo.es"
httpuser="authbasicuser"
httppass="authbasicpasswd"
backupDir=/home/$USER/Documentos/backup

#Check directory and remove index.html (or didn't upgrade)
if [ ! -d $backupDir/$url ];then
	mkdir -p $backupDir/$url
	if [ $? != 0 ];then
		printf "ERROR: Imposible crear %s\n" $backupDir/$url
		exit 1
	fi
fi
if [ -f $backupDir/$url/index.html ];then
	rm $backupDir/$url/index.html
	if [ $? != 0 ];then
		printf "ERROR: Imposible borrar %s\n" $backupDir/$url/index.html
		exit 1
	fi
fi

#Download with wget
printf "Destino backups:\t%s\n" $backupDir
printf "Sincronizando backup's desde %s\n" $scheme$url
wget -q --tries=3 -r -c --user=$httpuser --password=$httppass --directory-prefix=$backupDir $scheme$url
if [ $? != 0 ];then
	printf "ERROR: Se han producido errores en la sincronizacion\n"
	exit 1
fi
printf "Descarga correcta :)\n"