#!/bin/bash
# If no param is provided the script looks for the COMPUTERNAME and seeks special backup definition in a subfolder
# If no subfolder is provided the script uses the root folder backup definition /mnt/union/shared/bck2pbs/bck2pbs_source.txt
# if a param is provided the script looks for the special backup definition in the subfolder /mnt/union/shared/bck2pbs/$1
export PBS_REPOSITORY=bck_ops@pbs@kit.swallow-grue.ts.net:pbs-data
export PBS_PASSWORD=Wiry3-Finally-Juror-Glorious
export PBS_FINGERPRINT="8b:eb:4e:32:0e:26:18:c8:f8:83:40:3a:89:1d:5f:44:7a:e9:52:35:1c:94:24:ca:61:0d:80:63:8d:14:86:ad"
BACKUP_COMMAND=proxmox-backup-client
SRC_BASE_PATH=/mypool1/data/shared/bck2pbs
DST_PATH=/opt/scripts_local
SSH_HOST=""

source /opt/scripts_local/shared_functions.sh
sudo_check

echo "Specifiy location of backup definition."
if [ "$1" = "" ]; then
	# sudo ssh dbi@vmx-nas.swallow-grue.ts.net ls "$SRC_BASE_PATH/$HOSTNAME"
	if [ "$HOSTNAME" = "vmx-nas" ]; then
		sudo ls "$SRC_BASE_PATH/$HOSTNAME"
	else   # If script is run from another server than mynas
		ssh -o StrictHostKeyChecking=no root@vmx-nas.swallow-grue.ts.net ls "$SRC_BASE_PATH/$HOSTNAME" 
	fi
	DIR_EXISTS=$?
	if [ "$DIR_EXISTS" = "0" ] ; then 
		echo "Server subdir exists."
		SRC_DEFINITION_PATH="$SRC_BASE_PATH/$HOSTNAME/bck2pbs_source.txt" # /media/mypool1/data/shared/bck2pbs/$HOSTNAME/bck2pbs_source.txt
	else
		echo "No server subdir exists, using default (root) backup definition."
		SRC_DEFINITION_PATH="$SRC_BASE_PATH/bck2pbs_source.txt" # /media/mypool1/data/shared/bck2pbs/bck2pbs_source.txt
	fi
else
	echo "Param detected: using /mnt/union/shared/bck2pbs/$HOSTNAME/$1 as source definition."
	SRC_DEFINITION_PATH="$SRC_BASE_PATH/$HOSTNAME/$1" # /media/mypool1/data/shared/bck2pbs/$HOSTNAME/$1
fi

# Local copy of backup definition
echo "Copying backup definition locally."
if [ "$HOSTNAME" = "mynas" ]; then
	cp "$SRC_DEFINITION_PATH" "$DST_PATH/bck2pbs_source.txt" >/dev/null 2>&1
else   # If script is run from another server than mynas
	rsync -avP -e "ssh -o StrictHostKeyChecking=no" "$SSH_HOST/$SRC_DEFINITION_PATH" "$DST_PATH/bck2pbs_source.txt" >/dev/null 2>&1
fi

echo "Preparing backup."
sudo apt-get clean cache
source /opt/scripts_local/bck2pbs_source.txt
source /opt/scripts_local/bck2pbs_specific.sh

_get_architecture
if [ "$ARCHI" = "old_arm" ] ; then
	BACKUP_COMMAND=/usr/local/bin/pbs_client/proxmox-backup-client.sh
else
	BACKUP_COMMAND=proxmox-backup-client
fi

MYCOMMAND="$BACKUP_COMMAND backup $BACKUP_SOURCE"

$MYCOMMAND
