#!/bin/bash

# This is Rick Jerz's backup script for his production Moodle4, on his VPS.
# It keep 6 days of backup files.  Simple-minded approach... delete the x old files.
# Last revised: 2023-05-05.
# Last revised: 2023-12-20.

# Notes: config.php is also in the moodle backup, but I like to be double safe for this important file.
# 1) config.php, 2) the database, 3) moodle (just to keep the current version), and 4) moodledata
# Use today's date as prefix.

# Future improvements:
# Make an entry into the 'log' file

# #################
# (When sharing, requires the user to supply the moodle_vars.txt file.)
# #################

# These two variables control the script.
# What is the version of this moodle?
#  By changing this value, able to backup another moodle.
#  Note: this could be an umpty value, as in "".
mversion=4
#  By changing this value, able to control how many backups.
nversions=7
script_home="/your_pathto/scripts/"

echo
echo "-------------------------------"
echo "Backup Moodle$mversion files."
echo "-------------------------------"

# Variables in this script for the backup file names.
# Note: Moodle has three major components.
mybudbname="moodledb$mversion.sql"
mybudataname="moodledata$mversion"
mybumdappname="moodle$mversion"
mybumdconfig="config$mversion"

# The vars_file contain the other variables needed for this script to work.
vars_file=$script_home"m"$mversion"_vars.txt"

# Test to see if MySQL is running.  If not, exit.
# This was needed in MAMP, but on the server the database is always running.
#UP=$(pgrep mysql | wc -l)
#if [ "$UP" -ne 1 ]; then
#	echo "MySQL is down."
#	exit
#fi

# Read "sensitive" variables from other file.
# Does the variables file exist?  If not, exit.
if [ ! -f "$vars_file" ]; then
	echo "Missing variables file."
	exit
fi
source "$vars_file"

# Today's date
NOW=$(date +%F)
echo "Current date = "$NOW
# x days ago (change x to the number of backups)
WEEKAGO=$(date --date=$nversions" day ago" +%F)
echo "Old date = "$WEEKAGO

echo
echo "Backups are located in:"
echo "   "$mybudir
echo

# Backup up 3 components of Moodle.
echo "Backup the Moodle4 database"
mysqldump -u$mddbuser -p$mddbpass --opt --no-tablespaces -r"$mybudir"/$NOW-$mybudbname $mddbname

echo "Backup moodledata4"
tar cfz "$mybudir"/$NOW-$mybudataname.gz -P $mddatapath

echo "Backup moodle4"
tar cfz "$mybudir"/$NOW-$mybumdappname.gz -P $mdcode

echo "Backup config.php"
cp $mdcode/config.php $mybudir/$NOW-$mybumdconfig.php

# Delete the old (x days) files first
rm -f $mybudir/$WEEKAGO-$mybumdconfig.php
rm -f $mybudir/$WEEKAGO-$mybudbname
rm -f $mybudir/$WEEKAGO-$mybumdappname.gz
rm -f $mybudir/$WEEKAGO-$mybudataname.gz

# Show files in the backup directory
echo ""
ls -alh "$mybudir"

# Write this message to the log file.
echo ""
echo $(date)": Moodle"$mversion" Backup completed."
echo ""
