#!/bin/sh
#
# @license   http://www.gnu.org/licenses/gpl.html GPL Version 3
# @author    Julian Kalinowski <julakali@gmail.com>
# @copyright Copyright (c) 2013-2014 Julian Kalinowski
# @copyright Copyright (c) 2015-2024 openmediavault plugin developers
#
# 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
# 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/>.

set -e

. /etc/default/openmediavault
. /usr/share/openmediavault/scripts/helper-functions

# already set during postinst
OMV_RSNAPSHOT_CONFS_DIR=${OMV_RSNAPSHOT_CONFS_DIR:-"/var/lib/openmediavault/rsnapshot.d"}
OMV_RSNAPSHOT_CRONSCRIPT=${OMV_RSNAPSHOT_CRONSCRIPT:-"/var/lib/openmediavault/cron.d/rsnapshot"}

OMV_RSNAPSHOT_SCRIPTS_MASK=${OMV_RSNAPSHOT_SCRIPTS_MASK:-"755"}
OMV_RSNAPSHOT_DIRS_MASK=${OMV_RSNAPSHOT_DIRS_MASK:-"2775"}
OMV_RSNAPSHOT_STARTING_HOUR=${OMV_RSNAPSHOT_STARTING_HOUR:-"2"}
OMV_RSNAPSHOT_DISABLE_CRON=${OMV_RSNAPSHOT_DISABLE_CRON:-"0"}
OMV_RSNAPSHOT_LOGFILE=${OMV_RSNAPSHOT_LOGFILE:-"/var/log/rsnapshot.log"}

OMV_RSNAPSHOT_VERBOSE_LO=${OMV_RSNAPSHOT_VERBOSE_LO:-"2"}
OMV_RSNAPSHOT_VERBOSE_HI=${OMV_RSNAPSHOT_VERBOSE_HI:-"3"}
OMV_RSNAPSHOT_LOG_LEVEL=${OMV_RSNAPSHOT_LOG_LEVEL:-"2"}

# macros for xmlstarlet
GET_SOURCEFOLDER_PATH=${GET_SOURCEFOLDER_PATH=-m "//system/shares/sharedfolder[uuid=current()/src/sharedfolderref]" -v "concat(//system/fstab/mntent[uuid=current()/mntentref]/dir,'/',reldirpath)" -b}
GET_TARGETFOLDER_PATH=${GET_TARGETFOLDER_PATH=-m "//system/shares/sharedfolder[uuid=current()/dest/sharedfolderref]" -v "concat(//system/fstab/mntent[uuid=current()/mntentref]/dir,'/',reldirpath)" -b}
GET_SOURCE_RELDIR=${GET_SOURCE_RELDIR=-m "//system/shares/sharedfolder[uuid=current()/src/sharedfolderref]" -v "reldirpath" -b}

# rsnapshot path
RSNAPSHOT=/usr/bin/rsnapshot

if [ ! "${OMV_RSNAPSHOT_DISABLE_CRON}" = "1" ]; then

  hour1=${OMV_RSNAPSHOT_STARTING_HOUR}
  hour2=$(expr ${hour1} + 1)

  cat <<EOF > /etc/cron.d/openmediavault-rsnapshot
# Create cron file
# This is the cron file for openmediavault-rsnapshot.
# The file /var/lib/openmediavault/cron.d/rsnapshot will mirror
# the jobs that are configured in the plugin.
# m h 		dom mon dow user  command
5 *         * * *           root    /var/lib/openmediavault/cron.d/rsnapshot hourly
30 ${hour2}        * * *           root    /var/lib/openmediavault/cron.d/rsnapshot daily
0  ${hour2}        * * 1           root    /var/lib/openmediavault/cron.d/rsnapshot weekly
30 ${hour1}        1 * *           root    /var/lib/openmediavault/cron.d/rsnapshot monthly
00 ${hour1}        1 1 *           root    /var/lib/openmediavault/cron.d/rsnapshot yearly
EOF

fi

# Create the backup jobs. Every job gets its own config file, but their execution
# is managed through one single bash script that is executed by cron.

# create the configuration directory
mkdir -p ${OMV_RSNAPSHOT_CONFS_DIR}
# delete all previous configurations, as they're all created from scratch
rm -f ${OMV_RSNAPSHOT_CONFS_DIR}/rsnapshot-*

# Create a new rsnapshot script containing argument check
cat <<EOF > ${OMV_RSNAPSHOT_CRONSCRIPT}.tmp
#!/bin/bash
if [ -z "\$1" ]; then
	echo "No argument given. Should be one of: hourly,daily,weekly,monthly,yearly. UUID of backup job can be passed as second argument to execute a single job."
	exit 1
fi
mail=false
EOF

# void omv_get_mount_point (char *uuid)
# Get the mount point of the given shared folder
# @param The UUID of the shared folder
# @return The mount point, e.g /media/85732966-949a-4d8b-87d7-d7e6681f787e.
omv_get_mount_point() {
		xmlstarlet sel -t -m "//system/shares/sharedfolder[uuid='$1']" \
		  -v "//system/fstab/mntent[uuid=current()/mntentref]/dir" \
		  ${OMV_CONFIG_FILE} | xmlstarlet unesc
}

# Create the config files regardless if enabled or disabled.
xmlstarlet sel -t \
  -m "//services/rsnapshot/jobs/job" \
    -v "uuid" -n \
  -b \
  ${OMV_CONFIG_FILE} | xmlstarlet unesc |
  while read uuid; do
	  filename="${OMV_RSNAPSHOT_CONFS_DIR}/rsnapshot-${uuid}.conf"

	  sourcefolderref=$(omv_config_get "//services/rsnapshot/jobs/job[uuid='${uuid}']/src/sharedfolderref")

	  # determine the mountpoint of the source shared folder
	  mountpoint="$(omv_get_mount_point "${sourcefolderref}")"
	  label="$(lsblk -o mountpoint,label -n | grep -w "${mountpoint}" | awk '{print $2}' | uniq)"

	  if [ -e "${mountpoint}" ] && [ -n "${label}" ]; then
		# if mountpoint exists and filesystem has a label, use label as backup subdir name
		sourcelabel=${label}
	  else
		# else, use the fs mountpoint
		sourcelabel=${mountpoint#/}
	  fi

	  xmlstarlet sel -t -m "//services/rsnapshot/jobs/job[uuid='${uuid}']" \
		-o "# rsnapshot-${uuid}.conf" -n \
		-o "# This configuration file is auto-generated." -n \
		-o "# WARNING: Do not edit this file, your changes will be lost." -n \
		-o "config_version	1.2" -n \
		-o "snapshot_root	" ${GET_TARGETFOLDER_PATH} -o "/" -o "${sourcelabel}/" ${GET_SOURCE_RELDIR} -o "/"  -n \
		-o "no_create_root	1	# target root will be created before rsnapshot is running" -n \
		-i "hourly != 0" -o "retain	hourly	" -v "hourly" -n -b \
		-i "daily != 0" -o "retain	daily	" -v "daily" -n -b \
		-i "weekly != 0" -o "retain	weekly	" -v "weekly" -n -b \
		-i "monthly != 0" -o "retain	monthly	" -v "monthly" -n -b \
		-i "yearly != 0" -o "retain	yearly	" -v "yearly" -n -b \
		-i "erroroutputonly != 1" -o "verbose		${OMV_RSNAPSHOT_VERBOSE_HI}" -n -b \
		-i "erroroutputonly = 1" -o "verbose		${OMV_RSNAPSHOT_VERBOSE_LO}" -n -b \
		-o "loglevel	${OMV_RSNAPSHOT_LOG_LEVEL}" -n \
		-o "cmd_cp	/bin/cp" -n \
		-o "cmd_rm		/bin/rm" -n \
		-i "string-length(cmd_preexec) > 0" -o "cmd_preexec		" -v "cmd_preexec" -n -b \
		-i "string-length(cmd_postexec) > 0" -o "cmd_postexec		" -v "cmd_postexec" -n -b \
		-o "cmd_rsync	/usr/bin/rsync" -n \
		-o "cmd_logger	/usr/bin/logger" -n \
		-o "logfile		${OMV_RSNAPSHOT_LOGFILE}" -n \
		-o "rsync_long_args	" \
		-i "string-length(rsyncargs) > 0" -v "rsyncargs" -n -b \
		-i "string-length(rsyncargs) = 0" -o "--delete --numeric-ids --delete-excluded" -n -b \
		-o "one_fs	" -v "onefs" -n \
		-o "# no extra destination dir" -n \
		-o "backup	" ${GET_SOURCEFOLDER_PATH} -o "	./" -n \
		-o "rsync_numtries	" -v "numtries" -n \
		-o "lockfile	/var/run/rsnapshot-${uuid}.pid" -n \
		${OMV_CONFIG_FILE} | xmlstarlet unesc > ${filename}
	  chmod ${OMV_RSNAPSHOT_SCRIPTS_MASK} ${filename}

	  # append to rsnapshot script
	  xmlstarlet sel -t -m "//services/rsnapshot/jobs/job[uuid='${uuid}']" \
	    -i "enable = 0" -o "#### DISABLED ####" -n -b \
		-o "# backup " ${GET_SOURCEFOLDER_PATH} -o " to " ${GET_TARGETFOLDER_PATH} -n \
		-i "enable = 1" \
		-o "skip=false" -n \
		-i "hourly = 0" -o "if [ \"\$1\" = \"hourly\" ]; then skip=true; fi" -n -b \
		-i "daily = 0" -o "if [ \"\$1\" = \"daily\" ]; then skip=true; fi" -n -b \
		-i "weekly = 0" -o "if [ \"\$1\" = \"weekly\" ]; then skip=true; fi" -n -b \
		-i "monthly = 0" -o "if [ \"\$1\" = \"monthly\" ]; then skip=true; fi" -n -b \
		-i "yearly = 0" -o "if [ \"\$1\" = \"yearly\" ]; then skip=true; fi" -n -b \
			-o "if [ \"\$2\" = \"${uuid}\" ] || ([ -z \"\$2\" ] && [ \$skip = false ]); then" -n \
			-o "	targetdir=\"" ${GET_TARGETFOLDER_PATH} -o "/" -o "${sourcelabel}/" ${GET_SOURCE_RELDIR} -o "\"" -n \
			-o "	if [ ! -e \"\${targetdir}\" ]; then" -n \
			-i "erroroutputonly != 1" -o "		echo \"Creating target directory structure ... \"" -n -b \
			-o "		mkdir -p \"\${targetdir}\"" -n \
			-o "	fi" -n \
			-i "erroroutputonly != 1" -o "	echo \"Checking access rights on target directory structure ... \"" -n -b \
			-o "	while [ -n \"\${targetdir}\" ] && [ \"\${targetdir}\" != \"" ${GET_TARGETFOLDER_PATH} -o "\" ]; do" -n \
			-i "erroroutputonly != 1" -o "		echo \"... \${targetdir}\"" -n -b \
			-o "		chmod ${OMV_RSNAPSHOT_DIRS_MASK} \"\${targetdir}\"" -n \
			-o "		chgrp " -v "gid" -o " \"\${targetdir}\"" -n \
			-o "		targetdir=\"\${targetdir%/*}\"" -n \
			-o "	done" -n \
			-i "erroroutputonly != 1" -o "	mail=true" -n -b \
			-i "erroroutputonly != 1" -o "	echo \"starting \$1 backup for ${uuid}\"" -n -b \
			-o "	${RSNAPSHOT} -c \"${filename}\" \"\$1\"" -n \
			-o "fi" -n \
			-b \
		${OMV_CONFIG_FILE} | xmlstarlet unesc >> ${OMV_RSNAPSHOT_CRONSCRIPT}.tmp

  done

echo "if [ \$mail = true ]; then" >> ${OMV_RSNAPSHOT_CRONSCRIPT}.tmp
echo "	echo \"Backups finished.\"" >> ${OMV_RSNAPSHOT_CRONSCRIPT}.tmp
echo "fi" >> ${OMV_RSNAPSHOT_CRONSCRIPT}.tmp

# replace previous cronscript by newly created
mv ${OMV_RSNAPSHOT_CRONSCRIPT}.tmp ${OMV_RSNAPSHOT_CRONSCRIPT}
# make cronscript executable
chmod ${OMV_RSNAPSHOT_SCRIPTS_MASK} ${OMV_RSNAPSHOT_CRONSCRIPT}
