#!/bin/bash

. "$( cd -P "$( dirname "$0" )" && pwd )/.env"

server="$1"
failed=""

while IFS=';' read -r id username service target ; do
	if [ ! -d "/data/$service" ] ; then
		continue
	fi

	echo "   =   =   =====   =   =====   $service   =====   =   =====   =   =" 

	# Create passfile if not exists
	mkdir -p "$DATA_DIR/passphrase"
	passfile="$DATA_DIR/passphrase/$service"
	if [ ! -e "$passfile" ] ; then
		LC_ALL=C tr -dc A-Za-z0-9 </dev/urandom | head -c 257 > "$passfile"
	fi
	
	# Borg variables
	export BORG_REPO="backup-borg-server@127.0.0.1:/data/backup-borg-server/backups/$(hostname)/$service"
	export BORG_PASSPHRASE="$(cat "$passfile")"
	RSH='ssh -o StrictHostKeyChecking=no -p 12345'
	
	# Get specific backup files
	cd "/data/$service"
	BACKUP_LIST="$(ls -A)"
	if [ -x "/docker/$service/backup_list.sh" ] ; then
		BACKUP_LIST="$(/docker/$service/backup_list.sh)"
	fi
	if [ -z "$BACKUP_LIST" ] ; then
		continue
	fi
	echo "--------------> $BACKUP_LIST"
	
	borg init   --rsh "$RSH" --encryption repokey || true
	borg create --rsh "$RSH" --list --filter=AMCE --stats --show-rc "::$(date +%Y%m%d%H%M)" $BACKUP_LIST
	if [ "$?" -ne 0 ] ; then
		failed="$failed $service"
	fi

done < <(grep -v '^#' /docker/services.csv)        

if [ -n "$failed" ] ; then
	echo "FAILED"
	echo "$failed"
fi
