#!/bin/sh

backup_in_ve=0
restore_in_ve=0

backup_mode=0
restore_mode=0

ip=''
veid=''
backup_name="full-server-backup-"`date +%F`
backup_agent_archive_name="backup_agent.zip"
workdir="/var/cache"
destdir=`pwd`

usage()
{
	echo -e "Usage: $0 "
	echo -e "\t--backup-ct --ip=<ip> | --ct-id=<ctid> [ --backup-name=<name of backup> ] [ --work-dir=<path to working directory> ] [ --destination-dir=<path to destination directory>] - Create full server backup of the Panel on specified container and put into specified directory" 
	echo ""
	echo -e "\t--backup-local [ --backup-name=<name of backup> ] [ --work-dir=<path to working directory> ] [ --destination-dir=<path to destination directory> ] - Create full server backup of local Panel installation and put into specified directory" 
	echo ""
	echo -e "\t--restore-ct --ip=<ip> | --ct-id=<ctid> --backup-name=<name of backup> [ --work-dir=<path to working directory> ] - Restore specified backup into specified container"
	echo ""
	echo -e "\t--restore-local --backup-name=<name of backup> - Restore specified backup into local Panel installation"
	echo "Options:"
	echo -e "\t--backup-name=<filename> Optional for backup. Name of the backup file to be created. By default: full-server-backup-<current date>"
	echo -e "\t\t\t\t Required for restore. Name of the backup file to be restored."
	echo -e "\t--work-dir=<path>\t Optional. Path to directory where to put temporary files. By default: /var/cache"
	echo -e "\t--ip=<ip>\t\t Required for working with vz containers. IP of VZ container on this VZ node"
	echo -e "\t--ct-id=<ctid>\t\t Container ID"
	echo -e "\t--destination-dir=<path> Path to directory where to put dump file"
}

do_restore()
{
	if [ "$restore_in_ve" = 1 ]; then
		echo "Detected CTID: $veid"
		tmpdir=`vzctl exec2 $veid mktemp -d $workdir/XXXXXXX` 
		echo "Created temporary working directory: $tmpdir"
		productroot=`vzctl exec2 $veid grep PRODUCT_ROOT_D /etc/psa/psa.conf | awk '{print $2}'`
		echo "Uploading backup file to $tmpdir"
		private=`grep VE_ROOT /etc/vz/conf/"$veid".conf | awk 'BEGIN {FS="="} {gsub(/[\$VEID"]/,"",$2); print $2}'`
		cp "$backup_name" "$private"/"$veid"/"$tmpdir"/
		echo "Executing map file creation..."
		base_backup_name=`basename $backup_name`
		vzctl exec2 $veid "$productroot"/bin/pleskrestore --create-map "$tmpdir"/"$base_backup_name" -map "$tmpdir"/map
		echo "Map file is created. Executing full server restore..."
		vzctl exec2 $veid "$productroot"/bin/pleskrestore --restore "$tmpdir"/"$base_backup_name" -map "$tmpdir"/map -level server -verbose -debug -license
		echo "Restore finished"
	fi
	if [ "$restore_in_ve" = 0 ]; then
		productroot=`grep PRODUCT_ROOT_D /etc/psa/psa.conf | awk '{print $2}'`
		echo "Executing map file creation..."
		"$productroot"/bin/pleskrestore --create-map "$backup_name" -map map
		echo "Map file is created. Executing full server restore..."
		"$productroot"/bin/pleskrestore --restore "$backup_name" -map map -level server -verbose -debug -license
		echo "Restore finished"
	fi
}

do_backup()
{
	if [ ! -d $destdir ]; then
		mkdir -p $destdir
	fi

	if [ "$backup_in_ve" = 1 ]; then
		echo "Detected CTID: $veid"

		tmpdir=`vzctl exec2 $veid mktemp -d $workdir/XXXXXXX` 
		if [ "0" != $? ]; then
			echo "Unable to create temporary directory in $workdir"
			exit 1
		fi

		echo "Created temporary working directory: $tmpdir"
		echo "Detected path to container"
		private=`grep VE_ROOT /etc/vz/conf/"$veid".conf | awk 'BEGIN {FS="="} {gsub(/[\$VEID"]/,"",$2); print $2}'`
		if [ "" = "$private" ]; then
			echo "Unable to get path VE_ROOT. Please check value VE_ROOT in /etc/vz/conf/$veid.conf"
			vzctl exec2 $veid "rm -rf "$tmpdir" "
			exit 2
		fi

		echo "Uploading archive with backup agent to container..."
		cp "$backup_agent_archive_name" "$private"/"$veid"/"$tmpdir"/
		if [ "0" != $? ]; then
			echo "Uploading $backup_agent_archive_name to container $veid failed"
			exit 3
		fi

		echo "Extracting archive with backup agent..."
		vzctl exec2 $veid unzip -q "$tmpdir"/"$backup_agent_archive_name" -d "$tmpdir"
		if [ "0" != $? ]; then
			echo "Unable to extract archive with backup agent in $tmpdir"
			vzctl exec2 $veid "rm -rf "$tmpdir""
			exit 4
		fi

		echo "Executing full server backup..."
		vzctl exec2 $veid " cd "$tmpdir"; /usr/bin/perl -I"$tmpdir" "$tmpdir"/plesk_agent_manager server -vvvv --session-path="$tmpdir" --output-file="$tmpdir"/"$backup_name" --no-sign --validate-by-schema="$tmpdir"/plesk.xsd"
		if [ "0" != $? ]; then
			echo "Creation backup file is failed..."
			vzctl exec2 $veid xsltproc "$tmpdir"/result-report.xslt "$tmpdir"/migration.result
			cp "$private"/"$veid"/"$tmpdir"/psadump.log "$destdir"
			echo "More details about backup creation are in $destdir/psadump.log"
			exit 5
		fi
		echo "Backup file is created $tmpdir/$backup_name ..."
		vzctl exec2 $veid xsltproc "$tmpdir"/result-report.xslt "$tmpdir"/migration.result
		cp "$private"/"$veid"/"$tmpdir"/"$backup_name" "$destdir" 
		cp "$private"/"$veid"/"$tmpdir"/psadump.log "$destdir"
		echo "Removing temporary working directory..."
		vzctl exec2 $veid "rm -rf "$tmpdir" "
		echo "Created backup: $destdir/$backup_name"
		echo "More details about backup creation are in $destdir/psadump.log"
	fi
	if [ "$backup_in_ve" = 0 ]; then
		tmpdir=`mktemp -d $workdir/XXXXXXX`
		if [ "0" != $? ]; then
			echo "Unable to create temporary directory in $workdir"
			exit 1
		fi		
		echo "Created temporary working directory: $tmpdir"
		echo "Extracting backup agent to temporary working directory: $tmpdir"
		unzip -q "$backup_agent_archive_name" -d "$tmpdir"
		if [ "0" != $? ]; then
			echo "Unable to extract archive with backup agent in $tmpdir"
			rm -rf $tmpdir
			exit 4
		fi
		
		echo "Executing full server backup..."
		export LOCALLIB=1
		currdir=`pwd`
		cd $tmpdir
		/usr/bin/perl plesk_agent_manager server -vvvv --session-path="$destdir" --output-file="$destdir"/"$backup_name" --no-sign --validate-by-schema="$tmpdir"/plesk.xsd
		if [ "0" != $? ]; then
			cd $currdir
			echo "Creatin backup file is failed..."
			xsltproc "$tmpdir"/result-report.xslt "$destdir"/migration.result
			echo "More details about backup creation are in $destdir/psadump.log"
			exit 5
		fi
		cd $currdir 
		xsltproc "$tmpdir"/result-report.xslt "$destdir"/migration.result
		echo "Removing temporary working directory..."
		rm -rf $tmpdir
		unset LOCALLIB
		echo "Created backup: $destdir/$backup_name"
		echo "More details about backup creation are in $destdir/psadump.log"
	fi
}

if [ -n $1 ]; then
	while [ "x$1" != "x" ]; do
		param=`echo $1 | awk 'BEGIN {FS="="} {print $1}'`
		value=`echo $1 | awk 'BEGIN {FS="="} {print $2}'`
		case "$param" in
		"--backup-ct" )
			backup_in_ve=1
			backup_mode=1
		;;
		"--backup-local" )
			backup_mode=1
		;;
		"--ip" )
			veid=`vzlist | grep $value | awk {'print $1'}`
		;;
		"--ct-id" )
			veid=$value
		;;
		"--backup-name" )
			backup_name=$value
		;;
		"--restore-ct" )
			restore_in_ve=1
			restore_mode=1
		;;
		"--restore-local" )
			restore_mode=1
		;;
		"--work-dir" )
			workdir=$value
		;;
		"--destination-dir" )
			destdir=$value
		;;
		"--help" )
			usage
			exit 0
		;;
		* )
			echo "Unknown option or command $param"
			exit 1
		;;
		esac
		shift
	done
fi

if [ "$backup_mode" = "0" ] && [ "$restore_mode" = "0" ]; then
	usage
	exit 1
fi

if [ "$veid" != "" ]; then
	checkveid=`vzlist | awk '{print $1}' | grep -P ^$veid$`
	if [ "$checkveid" = "" ]; then
		echo "Container with id = $veid was not found"
		exit 1
	fi
fi

if [ "$backup_in_ve" = "1" ] && [ "$veid" = "" ]; then
	echo "Option --ip or --ct-id should be specified with command --backup-ct"
	exit 1
fi

if [ "$restore_in_ve" = "1" ] && [ "$veid" = "" ]; then
	echo "Option --ip or --ct-id should be specified with command --restore-ct"
	exit 1
fi

if [ "$backup_mode" = "1" ]; then
	do_backup 
fi

if [ "$restore_mode" = "1" ]; then
	do_restore 
fi
