#!/bin/bash

#
# db-backup by Christian Schwamborn
# v.1.0 2009-02-03
# v.1.0.1 2009-02-18
# v.1.0.2 2010-01-13 change dump from asscii to binary dumps
# v.1.0.3 2011-07-05 remove stderr from logger, modify su to use userenv
# v.1.0.4 2011-07-06 renamed to db-backup, add basic support for oracle xe database
# v.1.0.5 2012-03-14 add mysql support
# v.1.0.6 2012-06-06 minor fix with the loging in cleanold
# v.1.0.7 2012-10-22 minor fix with the config file and su executions
# v.1.0.8 2013-01-17 more stable "cleanold"
# v.1.0.9 2026-02-11 remove mandatory auth credentials
# v.1.0.10 2026-10-27 distinguish between mysql and mariadb
#
# restore with:
# su postgres -c "dropdb davical"
# su postgres -c "pg_restore -Cv -d template1 davical_2010-01-13_18-40-10.dump"
#

	# 0 = no output at all
	# 1 = normal operation messages
	# 2 = all messages
	Debug=1
	LogCmd="logger -t db-backup"
	budate=$(date +%F_%H-%M-%S)


	evalArgs() {

		if [ $# -eq 0 ]; then return; fi

		for arg in "$@"; do
			if expr 'index' "${arg}" '=' '>' '1' >/dev/null; then
				eval "${arg}"
			elif ! expr 'index' "${arg}" '=' >/dev/null; then
				command="${arg}"
			fi
		done
	}


	UserGroupOfFile() {

		local check_dir=${1}

		$(getfacl --tabular --absolute-names ${check_dir} | \
			awk     'BEGIN {}
				/^USER/ {print "export dir_owner=" $2}
				/^GROUP/ {print "export dir_group=" $2}
				END {}'
		)
	}


	mk_dump() {

		case "${dbtype}" in

			postgresql)
				mk_pgdump
			;;

			mysql)
				mk_mydump
			;;

			mariadb)
				mshow="mariadb-show"
				mdump="mariadb-dump"
				mk_mydump
			;;

			oracle)
				mk_oradump
			;;

			*)
				[ ${Debug} -gt 0 ] && ${LogCmd} "***_error_*** wrong database type specified in 'dbtype'"
			;;
		esac
	}


	mk_pgdump() {

		if [ -z "${database}" ]; then
			[ ${Debug} -gt 0 ] && ${LogCmd} "***_error_*** database not specified, i.e. 'database=davical'"
			exit 255
		elif ! su - "${dbuser}" -c "psql -c '\l' | grep -q ${database} >/dev/null" >/dev/null 2>&1; then
			[ ${Debug} -gt 0 ] && ${LogCmd} "***_error_*** specified database '${database}' not found"
			exit 255
		fi

		if su - "${dbuser}" -c "pg_dump -Fc -Z7 -f ${bupath}/${database}_${budate}.dump ${database}" >/dev/null 2>&1; then
			[ ${Debug} -gt 0 ] && ${LogCmd} "***_info_*** successfully dumped database '${database}' to '${bupath}/${database}_${budate}.dump'"
		else
			[ ${Debug} -gt 0 ] && ${LogCmd} "***_error_*** unable to dump database '${database}' as user '$(whoami)'"
			exit 255
		fi
	}


	mk_mydump() {

		dbcred_u=${dbauser:+"--user=${dbauser}"}
		dbcred_p=${dbapwd:+"--password=${dbapwd}"}

		if [ -z "${database}" ]; then
			[ ${Debug} -gt 0 ] && ${LogCmd} "***_error_*** database not specified, i.e. 'database=opsi'"
			exit 255
		elif ! su - "${dbuser}" -c "${mshow} ${dbcred_u} ${dbcred_p} |grep -q ${database}" >/dev/null 2>&1; then
			[ ${Debug} -gt 0 ] && ${LogCmd} "***_error_*** specified database '${database}' not found or wrong db credentials"
			exit 255
		fi

		if su - "${dbuser}" -c "${mdump} ${dbcred_u} ${dbcred_p} --create-options --routines --databases ${database} | gzip > ${bupath}/${database}_${budate}.dump.gz" >/dev/null 2>&1; then
			[ ${Debug} -gt 0 ] && ${LogCmd} "***_info_*** successfully dumped database '${database}' to '${bupath}/${database}_${budate}.dump.gz'"
		else
			[ ${Debug} -gt 0 ] && ${LogCmd} "***_error_*** unable to dump database '${database}' as user '$(whoami)'"
			exit 255
		fi
	}


	mk_oradump() {

		if ! [ -e "${oraenv}" ]; then
			[ ${Debug} -gt 0 ] && ${LogCmd} "***_error_*** no file specified to set up the oracle environment in 'oraenv'"
			exit 255
		fi

		if su - "${dbuser}" -c "source ${oraenv} ; echo quit | sqlplus "${dbauser}/${dbapwd}" | grep -q 'ORA-'" >/dev/null 2>&1; then
			[ ${Debug} -gt 0 ] && ${LogCmd} "***_error_*** unable to connect to oracel database with '${dbauser}/${dbapwd}'"
			exit 255
		elif su - "${dbuser}" -c "source ${oraenv} ; exp ${dbauser}/${dbapwd} file=${bupath}/${database}_${budate}.dump log=${bupath}/${database}_${budate}.log" >/dev/null 2>&1; then
			[ ${Debug} -gt 0 ] && ${LogCmd} "***_info_*** successfully dumped oracle database for user '${dbauser}' to '${bupath}/${database}_${budate}.dump"
			gzip ${bupath}/${database}_${budate}.dump
			gzip ${bupath}/${database}_${budate}.log
		else
			[ ${Debug} -gt 0 ] && ${LogCmd} "***_error_*** unable to dump oracle database for user '${dbauser}'"
			exit 255
		fi
	}


	cleanold() {

		local file2clean=""
		local clean_re="^.*${database}_([0-9]{4}-[0-9]{2}-[0-9]{2})_([0-9]{2})-([0-9]{2})-([0-9]{2}).*$"

		if [ -z "${database}" ]; then
			[ ${Debug} -gt 0 ] && ${LogCmd} "***_error_*** database not specified, i.e. 'database=davical'"
			exit 255
		fi

		find ${bupath} -regextype posix-extended -regex "${clean_re}" -type f -print | \
			while read file2clean; do
				file_date=$(echo ${file2clean} | sed -r -e "s,${clean_re},\1 \2:\3:\4,")
				if [ $(date --date "${file_date}" +%s) \
					-le \
					$(date --date "${keep} days ago" +%s) ]; then

					if rm -f "${file2clean}"; then
						[ ${Debug} -ge 0 ] && ${LogCmd} "***_info_*** removed old backup: '${file2clean}'"
					else
						[ ${Debug} -ge 0 ] && ${LogCmd} "***_error_*** failed to remove '${file2clean}'"
					fi
				fi
			done
	}


evalArgs "$@"
config=${config:-"/etc/db-backup/db-backup.conf"}
[ -e "${config}" ] && . "${config}"
bupath=${bupath:-"/var/lib/db-backup/postgres"}
keep=${keep:-30}
dbuser=${dbuser:-"postgres"}
dbtype=${dbtype:-"postgresql"}
dbauser=${dbauser:-""}
dbapwd=${dbapwd:-""}
oraenv=${oraenv:-"/usr/lib/oracle/xe/oracle_env.sh"}
mshow="mysqlshow"
mdump="mysqldump"

if ! id "${dbuser}" >/dev/null 2>&1; then
	[ ${Debug} -gt 0 ] && ${LogCmd} "***_error_*** user '${dbuser}' does not exist"
	exit 255
fi

if ! [ -d ${bupath} ]; then
	if ! mkdir -p ${bupath}; then
		[ ${Debug} -gt 0 ] && ${LogCmd} "***_error_*** unable to create backup directory '${bupath}'"
		exit 255
	else
		[ ${Debug} -gt 1 ] && ${LogCmd} "***_info_*** successfully created backup directory '${bupath}'"
	fi
fi

dbuserGroup=$(id "${dbuser}" | sed -r -e 's|^.*gid=[[:digit:]]+\(([[:alnum:]]+)\).*$|\1|g')
UserGroupOfFile ${bupath}
if [ "${dbuser}" != "${dir_owner}" ] || [ "${dbuserGroup}" != "${dir_group}" ]; then
	if ! chown -R ${dbuser}:${dbuserGroup} ${bupath}; then
		[ ${Debug} -gt 0 ] && ${LogCmd} "***_error_*** unable to change owner of '${bupath}' to '${dbuser}'"
		exit 255
	else
		[ ${Debug} -gt 1 ] && ${LogCmd} "***_info_*** successfully changed owner of '${bupath}' to '${dbuser}'"
	fi
fi

if [ "${dbtype}" == "oracle" ]; then
	database="oracle"
fi

case "${command}" in

	dump)
		mk_dump
	;;

	auto)
		mk_dump
		cleanold
	;;

	cleanup)
		cleanold
	;;

	*)
		echo "$0 dump|auto|cleanup database=<db-name> [keep=<days>]"
		echo "  [bupath=<path to backups>] [dbuser=<database-username>]"
		echo "  [dbtype=<postgresql|mysql|mariadb|oracle>] [dbauser=<username> dbapwd=<password>]"
		echo "  [oraenv=<path to a script that sets up the oracel environment>]"
		echo "  [config=<path to a config file>]"
		echo "Commands:"
		echo "  dump = just dump the thing"
		echo "  auto = dump it and remove the dumps older than X days specified in keep"
		echo "  cleanup = just clean up the old dumps"
		echo "Options Defaults:"
		echo "  config=/etc/db-backup/db-backup.conf"
		echo "  bupath=/var/lib/db-backup/postgres"
		echo "  keep=30"
		echo "  dbuser=postgres"
		echo "  dbtype=postgresql"
		echo "  dbauser="
		echo "  dbapwd="
		echo "  oraenv=/usr/lib/oracle/xe/oracle_env.sh"
		echo "All options can be placed in a configuration file which will be sourced at"
		echo "the start of the script, but they're overwritten by command line options."
		exit 0
	;;
esac

