#!/bin/sh

NAME="urbackup_srv"
BASEDIR=`dirname $0`
PREFIX=`dirname $BASEDIR`
DAEMON=$PREFIX/sbin/urbackup_srv
if ! test -x $DAEMON
then
	PREFIX=/usr/local
    DAEMON=$PREFIX/sbin/urbackup_srv
	if ! test -x $DAEMON
	then
		PREFIX=/usr
		DAEMON=$PREFIX/sbin/urbackup_srv
	fi
fi

DAEMON_DIR="/var"
if ! test -f $DAEMON_DIR/urbackup/backup_server.db
then
    DAEMON_DIR="$PREFIX/var"
    if ! test -f $DAEMON_DIR/urbackup/backup_server.db
    then
		DAEMON_DIR="/usr/local/var"
		if ! test -f $DAEMON_DIR/urbackup/backup_server.db
		then
			DAEMON_DIR="/var"
			if ! test -d $DAEMON_DIR/urbackup
			then
				DAEMON_DIR="$PREFIX/var"
				if ! test -d $DAEMON_DIR/urbackup
				then
					DAEMON_DIR="/usr/local/var"
					if ! test -d $DAEMON_DIR/urbackup
					then
						DAEMON_DIR="/usr/var"
					fi
				fi
			fi
		fi
    fi
fi



DAEMON_LIBS="$PREFIX/lib"
if ! test -e $DAEMON_LIBS/liburbackupserver.so
then
	DAEMON_LIBS="$PREFIX/lib64"
	if ! test -e $DAEMON_LIBS/liburbackupserver.so
	then
		DAEMON_LIBS="/lib"
	fi
fi

PLUGIN_URL="--plugin $DAEMON_LIBS/liburbackupserver_urlplugin.so"
if ! test -e $DAEMON_LIBS/liburbackupserver_urlplugin.so
then
	PLUGIN_URL=""
fi

PLUGIN_BDB="--plugin $DAEMON_LIBS/liburbackupserver_bdbplugin.so"
if ! test -e $DAEMON_LIBS/liburbackupserver_bdbplugin.so
then
	PLUGIN_BDB=""
fi

PLUGIN_CRYPTO="--plugin $DAEMON_LIBS/liburbackupserver_cryptoplugin.so"
if ! test -e $DAEMON_LIBS/liburbackupserver_cryptoplugin.so
then
	PLUGIN_CRYPTO=""
fi

SNAPSHOT_HELPER="$PREFIX/bin/urbackup_snapshot_helper"
if ! test -x $SNAPSHOT_HELPER
then
	echo "Info: Snapshot helper not found. Btrfs mode will not work."
fi

HAS_MOUNTVHD=1
if ! test -e $DAEMON_LIBS/liburbackupserver_fuseplugin.so
then
	HAS_MOUNTVHD=0
fi	

HTTP_PLUGIN="--plugin $DAEMON_LIBS/liburbackupserver_httpserver.so"
DAEMON_PLUGINS="$PLUGIN_BDB $PLUGIN_URL $PLUGIN_CRYPTO --plugin $DAEMON_LIBS/liburbackupserver_fsimageplugin.so --plugin $DAEMON_LIBS/liburbackupserver.so --http_root $DAEMON_DIR/urbackup/www --workingdir $DAEMON_DIR --snapshot_helper $SNAPSHOT_HELPER"
S_DAEMON="--daemon"

print_help()
{
	echo "UrBackup server wrapper script. Starts UrBackup Server."
	echo "Parameters:"
	echo "--fastcgi_port {port}	Specifies the port where UrBackup server will listen for FastCGI connections. Default: 55413"
	echo "--http_port {port}	Specifies the port where UrBackup server will listen for HTTP connections. Default: 55414"
	echo "--logfile {file}	Specifies the log file name. Default: urbackup.log"
	echo "--loglevel {debug|info|warn|error}	Specifies the log level. Possible values: debug, info, warn, error. Default: warn"
	echo "--no_daemon	Do not start as a daemon"
	echo "--pidfile {file}		Save pid of daemon in file"
	echo "--sqlite_tmpdir {tmpdir}	Specifies the directory sqlite uses to store temporary tables"
	echo "--verify_hashes		Verifies a file backup"
	echo "--delete_verify_failed		Delete file entries of files with failed verification"
	echo "--remove_unknown		Remove unknown backups from storage and internal database"
	echo "--reset_pw {pw}		Resets the pw"
	echo "--cleanup {X}			Cleans up X %|M|G|T from backup storage"
	echo "--repair_database		Tries to repair the database"
	echo "--defrag_database		Defragments the internal database and deletes the file entry cache"
	echo "--export_auth_log		Export authentication log"
	echo "--broadcast_interfaces   List of network interfaces from which to send broadcasts (separated by ,)"
	echo "--user			   Start as specific user (default: urbackup)"
	echo "--decompress {file}	Decompress a UrBackup compressed file"
	echo "--assemble {Image_C_XXX.vhdz};{Image_SYSVOL_XXX.vhdz}"
	echo "                Assemble VHD(Z) volumes into one disk VHD file. Requires --assemble_output."
	echo "--assemble_output {path/Disk.vhd}  Location where disk VHD is written when assembling"
	if [ "x$HAS_MOUNTVHD" = "x1" ]; then
		echo "--mountvhd {file} 	Mount the VHD(z)-file"
		echo "--mountpoint {dir}	Mount the VHD(z)-file at this mountpoint"
		echo "--tempmount {dir}		Use this directory as temporary mountpoint"
	fi
	echo ""
	echo "Have a nice day!"
	exit 0
}

print_version()
{
	echo "UrBackup Server v1.4.14"
	echo "Copyright (C) 2011-2015 Martin Raiber"
	echo "This is free software; see the source for copying conditions. There is NO"
	echo "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
	exit 0
}

RUN_IN_GDB=0
RUN_IN_VALGRIND=0
MOUNTVHD=""
MOUNTVHD_TMPDIR=""
MOUNTVHD_MOUNTPOINT=""

GETOPT=getopt

if test -x $PREFIX/bin/getopt
then
	GETOPT=$PREFIX/bin/getopt
fi

if `$GETOPT -T > /dev/null 2>&1`; [ $? = 4 ]; then
	FASTCGI_PORT=55413
	HTTP_PORT=55414
	LOGFILE="urbackup.log"
	LOGLEVEL="warn"
	PIDFILE="/var/run/urbackup_srv.pid"
	SQLITE_TMPDIR=""
	VERIFY_HASHES=""
	DELETE_VERIFY_FAILED=""
	RESET_PW1=""
	RESET_PW2=""
	CLEANUP=""
	BROADCAST_INTERFACES=""
	URB_USER="urbackup"	
	DECOMPRESS=""
	ASSEMBLE=""
	ASSEMBLE_OUTPUT=""
	TEMP=`$GETOPT -o f:h:l:v -n start_urbackup_server --long version,no_daemon,help,fastcgi_port:,http_port:,logfile:,loglevel:,pidfile:,sqlite_tmpdir:,verify_hashes:,reset_pw:,cleanup:,remove_unknown,cleanup_database,repair_database,broadcast_interfaces:,run_in_gdb,run_in_valgrind,user:,defrag_database,export_auth_log,mountvhd:,mountpoint:,tempmount:,decompress:,delete_verify_failed,assemble:,assemble_output: -- "$@"`
	eval set -- "$TEMP"
	while true ; do
		case "$1" in
			-f|--fastcgi_port) FASTCGI_PORT="$2"; shift 2 ;;
			-h|--http_port) HTTP_PORT="$2"; shift 2 ;;
			-l|--logfile) LOGFILE="$2"; shift 2 ;;
			-v|--loglevel) LOGLEVEL="$2"; shift 2 ;;
			--pidfile) PIDFILE="$2"; shift 2 ;;
			--no_daemon) S_DAEMON=""; shift ;;
			--help) print_help ;;
			--version) print_version ;;
			--sqlite_tmpdir) SQLITE_TMPDIR="--sqlite_tmpdir $2"; shift 2 ;;
			--verify_hashes) VERIFY_HASHES="--verify_hashes $2"; shift 2 ;;
			--delete_verify_failed) DELETE_VERIFY_FAILED="--delete_verify_failed true"; shift ;;
			--reset_pw) RESET_PW1="--set_admin_pw"; RESET_PW2="$2"; shift 2 ;;
			--cleanup) CLEANUP="--app cleanup --cleanup_amount $2"; shift 2;;
			--remove_unknown) CLEANUP="--app remove_unknown"; shift ;;
			--cleanup_database) CLEANUP="--app cleanup_database"; shift ;;
			--repair_database) CLEANUP="--app repair_database"; shift ;;
			--broadcast_interfaces) BROADCAST_INTERFACES="--broadcast_interfaces $2"; shift 2 ;;
			--run_in_gdb) RUN_IN_GDB=1; shift ;;
			--run_in_valgrind) RUN_IN_VALGRIND=1; shift ;;
			--user) URB_USER="$2"; shift 2;;
			--defrag_database) CLEANUP="--app defrag_database"; shift ;;
			--export_auth_log) CLEANUP="--app export_auth_log"; URB_USER=""; shift ;;
			--mountvhd) MOUNTVHD="$2"; shift 2 ;;
			--mountpoint) MOUNTVHD_MOUNTPOINT="$2"; shift 2;;
			--tempmount) MOUNTVHD_TMPDIR="$2"; shift 2;;
			--decompress) DECOMPRESS="$2"; shift 2 ;;
			--assemble) ASSEMBLE="$2"; shift 2;;
			--assemble_output) ASSEMBLE_OUTPUT="$2"; shift 2;;
			--) shift; break ;;
			*) echo "error!" ; exit 1 ;;
		esac
	done
	
	if [ "x$VERIFY_HASHES" != "x" ]
	then
		LOGLEVEL="info"
		S_DAEMON="--no-server"
		HTTP_PLUGIN=""
	fi
	
	if [ "x$RESET_PW1" != "x" ]
	then
		LOGLEVEL="debug"
		S_DAEMON="--no-server"
		HTTP_PLUGIN=""
	fi
	
	if [ "x$CLEANUP" != "x" ]
	then
		LOGLEVEL="debug"
		S_DAEMON="--no-server"
		HTTP_PLUGIN=""
	fi
	
	if [ "x$RUN_IN_GDB" = "x1" ]
	then
		S_DAEMON=""
	fi
	
	if [ "x$RUN_IN_VALGRIND" = "x1" ]
	then
		S_DAEMON="--plugin $DAEMON_LIBS/liburbackupserver_fsimageplugin.so"
	fi
	
	if [ "x$MOUNTVHD_MOUNTPOINT" != "x" ]; then
		if [ "x$MOUNTVHD" = "x" ]; then
			echo "Please specify the VHD file via the --mountvhd argument"
			exit 1
		fi
	fi
	
	USER_ARG=""
	if [ "x$URB_USER" != "x" ]; then
		USER_ARG="--user $URB_USER"
	fi
	
	if [ "x$MOUNTVHD" != "x" ]
	then
		if [ "x$MOUNTVHD_MOUNTPOINT" = "x" ]; then
			echo "Please specify the mountpoint via the --mountpoint argument"
			exit 1
		fi
		if [ "x$MOUNTVHD_TMPDIR" = "x" ]; then
			MOUNTVHD_TMPDIR=`mktemp -d`
		fi
		echo "Using temporary mountpoint $MOUNTVHD_TMPDIR"
		S_DAEMON="--daemon"
		DAEMON_ARGS="--plugin $DAEMON_LIBS/liburbackupserver_fsimageplugin.so --plugin $DAEMON_LIBS/liburbackupserver_fuseplugin.so --mount $MOUNTVHD --mountpoint $MOUNTVHD_TMPDIR --loglevel debug"
	elif [ "x$DECOMPRESS" != "x" ]
	then
		DAEMON_ARGS="--plugin $DAEMON_LIBS/liburbackupserver_fsimageplugin.so --decompress $DECOMPRESS --loglevel debug"
		S_DAEMON=""
	elif [ "x$ASSEMBLE" != "x" ]
	then
		if [ "x$ASSEMBLE_OUTPUT" == "x" ]
		then
			echo "Error: Output file (--assemble_output) not set"
			exit 1
		fi
		
		DAEMON_ARGS="--plugin $DAEMON_LIBS/liburbackupserver_fsimageplugin.so --assemble \"$ASSEMBLE\" --output_file \"$ASSEMBLE_OUTPUT\" --loglevel debug"
		S_DAEMON=""
	else
		DAEMON_ARGS="--port $FASTCGI_PORT --logfile /var/log/$LOGFILE --loglevel $LOGLEVEL --http_port $HTTP_PORT --pidfile $PIDFILE $USER_ARG $SQLITE_TMPDIR $VERIFY_HASHES $DELETE_VERIFY_FAILED $CLEANUP $BROADCAST_INTERFACES"
	fi
else
	DAEMON_ARGS="--user urbackup $*"
fi


# Exit if the package is not installed
if [ ! -x $DAEMON ]
then
    echo "Server binary not found"
fi

ulimit -n 100000 > /dev/null 2>&1

export MPLCONFIGDIR=$DAEMON_DIR/urbackup

if [ "x$MOUNTVHD" = "x" ]
then
	DAEMON_ARGS="$DAEMON_PLUGINS $HTTP_PLUGIN $DAEMON_ARGS"
fi

if [ "x$RUN_IN_GDB" = "x1" ]
then
	cd $DAEMON_DIR
	gdb --args $DAEMON $S_DAEMON $DAEMON_ARGS
elif [ "x$RUN_IN_VALGRIND" = "x1" ]
then
	cd $DAEMON_DIR
	valgrind --tool=memcheck --leak-check=full --track-origins=yes --vgdb=yes $DAEMON $S_DAEMON $DAEMON_ARGS --allow_shutdown true --leak_check true
elif [ "x$MOUNTVHD" != "x" ]
then
	echo "Loading FUSE kernel module..."
	modprobe fuse
	echo "Starting VHD background process.."
	$DAEMON $S_DAEMON $DAEMON_ARGS
	sleep 3
	echo "Starting mounting..."
	mount -v -o loop,ro "$MOUNTVHD_TMPDIR/volume" "$MOUNTVHD_MOUNTPOINT"
else
	if [ "x$DECOMPRESS" = "x" ]; then
		cd $DAEMON_DIR
	fi
	exec $DAEMON $S_DAEMON $DAEMON_ARGS $RESET_PW1 "$RESET_PW2"
fi
