#!/bin/sh
#
# Copyright (C) Matthieu Patou <mat@matws.net> 2010-2011
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Revised 2013-09-25, Brian Martin, as follows:
#    - Allow retention period ("DAYS") to be specified as a parameter.
#    - Allow individual positional parameters to be left at the default
#      by specifying "-"
#    - Use IS0 8601 standard dates (yyyy-mm-dd instead of mmddyyyy).
#    - Display tar exit codes when reporting errors.
#    - Don't send error messages to /dev/null, so we know what failed.
#    - Suppress useless tar "socket ignored" message.
#    - Fix retention period bug when deleting old backups ($DAYS variable
#      could be set, but was ignored).
#
# Adapted 2017-2018, EOLE, as follows:
#    - Allow date format to be specified as a parameter
#    - Write a report in destination folder with rst-like formatting
#    - Suppress "/" suppression messages by changing directory and using
#      relative paths.
#    - When launch with parameter, do not save tar file with history
#      only the contents.

function title()
{
	case $1 in
		1)
			symbol="="
			;;
		2)
			symbol="~"
			;;
		3)
			symbol="-"
			;;
		*)
			;;
	esac
	nbchar=${#2}
	echo "${2}"
	for i in $(seq $nbchar)
	do
		echo -n "${symbol}"
	done
	echo
	echo
}

function listitem() 
{
	echo $1 | sed -e 's/\([^\\]\) \(.\)/\1\n  - \2/g' -e 's/^\(.\+\)$/  - \1/'
}

ROOT=/
. /etc/samba/samba_backup.conf
if [ -n "$1" ] && [ "$1" = "-h" -o "$1" = "--usage" ]; then
	echo "samba_backup [provisiondir] [destinationdir] [retpd]"
	echo "Will backup your provision located in provisiondir to archive stored"
	echo "in destinationdir for retpd days. Use - to leave an option unchanged."
	echo "Default destinationdir: $WHERE"
	echo "Default destinationdir: $DAYS"
	exit 0
fi
if [ -n "$1" ] && [ "$1" = "cron" ]; then
	bareos_mode=0
else
	bareos_mode=1
fi

if [ "$bareos_mode" = "0" ]; then
	WHEN=`date ${WHEN_FORMAT}`
	REPORT="${WHERE%/}/samba_backup_${WHEN}.report"
	ENDNAME=".${WHEN}.tar.bz2"
else
	WHEN='pre'
	REPORT="${WHERE%/}/samba_backup.report"
	ENDNAME=".tar"
	WHERE=$WHERE/bareos
	rm -rf "${WHERE}/*"
fi

if [ ! -d $WHERE ]; then
	echo "Missing backup directory $WHERE"
	mkdir -p $WHERE
fi

title 1 "Log of backup on $WHEN" > $REPORT

for d in $FROMWHERE;do
	title 2 "Backing up $d" >> $REPORT
	n=`echo $d | sed 's/\//_/g'`
	filename="${WHERE}/samba4${n}${ENDNAME}"
	if [ "`basename $d`" = "private" ]; then
		title 3 "Removing old *.ldb.bak copies" >> $REPORT
		ldb_bak="$(find $ROOT/$d -name \"*.ldb.bak\")"
		if [ -n "${ldb_bak}" ]
		then
			rm $ldb_bak
			listitem $ldb_bak >> $REPORT
		else
			echo "No old backup to remove" >> $REPORT
		fi
		echo >> $REPORT

		title 3 "Copying *.ldb files" >> $REPORT
		for ldb in `find $ROOT/$d -name "*.ldb"`; do
			tdbbackup $ldb
			Status=$?	# Preserve $? for message, since [ alters it.
			if [ $Status -ne 0 ]; then
				echo "Error while backing up $ldb - status $Status" | tee -a $REPORT
				exit 1
			else
				listitem "$ldb" >> $REPORT
			fi
		done
		echo >> $REPORT
		
		title 3 "Creating archives" >> $REPORT
		# Run the backup.
		#    --warning=no-file-ignored set to suppress "socket ignored" messages.
		tar cjf $filename  -C $ROOT ${d#/} --xattrs --exclude=\*.ldb --warning=no-file-ignored --warning=no-file-changed --transform 's/.ldb.bak$/.ldb/'
		Status=$?	# Preserve $? for message, since [ alters it.
		if [ $Status -ne 0 -a $Status -ne 1 ]; then	# Ignore 1 - private dir is always changing.
			echo "Error while archiving $filename - status = $Status" | tee -a $REPORT
			exit 1
		else
			echo "$ROOT/$d archived in $filename: " >> $REPORT
			echo >> $REPORT
			listitem "$(tar -tf $filename)" >> $REPORT
		fi
		echo >> $REPORT
		find $ROOT/$d -name "*.ldb.bak" -exec rm {} \;
	else
		title 3 "Creating archives" >> $REPORT
		# Run the backup.
		#    --warning=no-file-ignored set to suppress "socket ignored" messages.
		tar cjf $filename -C $ROOT  ${d#/} --xattrs --warning=no-file-ignored --warning=no-file-changed
		Status=$?	# Preserve $? for message, since [ alters it.
		if [ $Status -ne 0 ]; then
			echo "Error while archiving $filename - status = $Status"
			exit 1
		else
			echo "$ROOT/$d archived in $filename: " >> $REPORT
			echo >> $REPORT
			listitem "$(tar -tf  $filename)" >> $REPORT
		fi
		echo >> $REPORT
	fi

	if [ ! "$bareos_mode" = "0" ]; then
		tar xf $filename -C $WHERE
		rm $filename
	fi
done
echo "End of backup" >> $REPORT
echo >> $REPORT

title 1 "Cleaning…" >> $REPORT
if [ "$bareos_mode" = "0" ]; then
	old_archives=$(find $WHERE -name "samba4_*bz2" -mtime +$DAYS)
	[ -n "${old_archives}" ] && rm  ${old_archives}
	echo "Removed $(echo ${old_archives} | wc -w) archives older than $DAYS days." >> $REPORT
fi
exit 0
