Website backup script

Voorbeeld script

Geschreven door Peter van Gemert

Op 12 september 2023


#! /bin/bash  
############  
# website-backup.sh  
# Syntax  : website-backup.sh  
# Purpose : Create backup of apache config and documentroot.  
#  
#  
#  
#  
#  
  
# Bepaald vandaag datum string
nu=$(date "+%Y%m%d_%H%M%S")  
  
# Zet variabelen
documentRoot="/remote/nfs/website/" # Let op, trailing slash * is verplicht  
apacheRoot="/etc/apache2/"          # Let op, trailing slash * is verplicht  
syncDir="/backup/rsync"  

backupDir="/backup/archives"  
configArchive="${backupDir}/apacheconfig-${nu}.tgz"
websiteArchive="${backupDir}/documentroot-${nu}.tgz"

logDir="/var/log/webiste-backup"
logFile="${logDir}/website-backup-${nu}.log"  
configLog="${logDir}/apacheconfig-${nu}.log"
websitelog="${logDir}/documentroot-${nu}.log"
  
echo "Start backup: $(date)" >>${logFile} 2>&1
  
# Maak log directory
mkdir -p ${logDir} 2>/dev/null  
  
# Controleer op effective user
effectiveUser=$(whoami)  
if [[ $effectiveUser != root ]] ; then  
   echo "Error: $(basename $0): Not root. Should be run as root." >>${logFile} 2>&1
   exit 2  
fi  
  
# Controleer backupDir
mkdir -p ${backupDir} 2>/dev/null  
cd ${backupDir}  
if [[ $? -ne 0 ]] ; then  
   echo "Error: $(basename $0): Could not access ${backupDir}" >>${logFile} 2>&1
   exit 3  
fi  
cd /tmp  
  
# Controleer syncDir
mkdir -p ${syncDir} 2>/dev/null  
cd ${syncDir}  
if [[ $? -ne 0 ]] ; then  
   echo "Error: $(basename $0): Could not access ${syncDir}" >>${logFile} 2>&1
   exit 4  
fi  
  
# Shutdown Apache2 
systemctl stop apache2  
  
# Sync gewenste bestanden
rsync -ogpcrRlvv ${documentRoot} ${apacheRoot} ${syncDir}  >>${logFile} 2>&1
if [[ $? -ne 0 ]] ; then  
   echo "Error: $(basename $0): Rsync failed. No backup was made." >>${logFile} 2>&1
   systemctl start apache2  
   systemctl status apache2 >>${logFile} 2>&1
   exit 5  
fi  
  
# Start Apache2  
systemctl start apache2  
systemctl status apache2 >>${logFile} 2>&1
  
# Create backups of website
echo "Create Document root backup" >>${logFile} 2>&1
cd ${syncDir}/remote/nfs/website  
tar -czvf ${websiteArchive} . >${websiteLog} 2>&1

# Create backup of apache config
echo "Create Apache config backup" >>${logFile} 2>&1
cd ${syncDir}/etc/apache2  
tar -czvf ${configArchive} . >${configLog}> 2>&1

echo "Backup done: $(date)" >>${logFile} 2>&1
exit 0
  
# eos