#!/bin/bash
export PBS_REPOSITORY=bck_adm@pbs@kut-pbs.swallow-grue.ts.net:kut-backup
export PBS_PASSWORD=Wiry3-Finally-Juror-Glorious
export PBS_FINGERPRINT="58:0d:62:d1:64:18:8a:7b:fd:56:71:45:47:28:53:a3:dc:9e:b5:74:4b:d2:f3:1f:56:6c:14:d5:98:13:43:40"
export BACKUP_SOURCE="etc.pxar:/etc opt.pxar:/opt var.pxar:/var usr.pxar:/usr/local home.pxar:/home root.pxar:/root"
export BACKUP_EXCLUDE="--exclude={/var/lib/vz/**,/media/**,/mnt/**}"
apt-get clean cache
export HC_ID=$1
export BCK_INLUDE=$2
export BACKUP_COMMAND=""
export HC_COMMAND=""



[ "test$HC_ID" != "test"  ] && curl -fsS -m 10 --retry 5 -o /dev/null https://hc.noxs.me/ping/"$HC_ID"/start

bck_include() {
# Includes in  the backup set if $1 is a file or a directory
# This is necessary to have a backup without errors when the requested dir does not exists
# e.g. /etc/pve exists only on Proxmox host machines
if [ -d "$1" ] || [ -f "$1" ]
then
        INCLUDE_CLEAN=$(escape_spec_char "$1")
        INCLUDE="$INCLUDE $INCLUDE_CLEAN.pxar:$1"  
fi
}

escape_spec_char()
{
	# (rev | sed -e 's/|/`/' | rev) --> reverse the string and replace the 1st / (last / before rev) with nothing then rev again
	# (sed -e 's/\///') --> replace the 1st / with nothing 
	# (-e 's/\//\-/g') --> replace the following / with _
	# -e ()'s/\./\_/g') --> replace the . with _
	echo "$1" | rev | sed -e 's/|/`/' | rev | sed -e 's/\///' -e 's/\//\-/g' -e 's/\./\_/g'  
}

strings=(
    /etc /opt /var /usr/local /home /root
)
for i in "${strings[@]}"; do
	bck_include "$i"
done

get_architecture()
{
ARCHI=""
case $(uname -m) in
    i386 | i686)   	ARCHI="386" ;;
    x86_64) 		ARCHI="amd64" ;;
    arm | aarch64)    		dpkg --print-architecture | grep -q "arm64" && ARCHI="arm64" || ARCHI="arm" ;;
	armv7l)			ARCHI="old_arm" ;;
	*)   			echo "Unable to determine system architecture."; exit 1 ;;
esac
}

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
# Healthcheck ID provided
if [ -n "$HC_ID"  ] ; then
	HC_COMMAND="curl -fsS -m 10 --retry 5 -o /dev/null https://hc.noxs.me/ping/'$HC_ID'"
else
	HC_COMMAND="echo done"
fi

( "$BACKUP_COMMAND" backup $BACKUP_EXCLUDE $BACKUP_SOURCE ) && $HC_COMMAND

