]> git.p6c8.net - nextcloud-backup-restore.git/blob - NextcloudBackup.sh
8d8149c7f4b203fccf2100f80b80db0e7ecba751
[nextcloud-backup-restore.git] / NextcloudBackup.sh
1 #!/bin/bash
2
3 #
4 # Bash script for creating backups of Nextcloud.
5 #
6 # Version 2.3.1
7 #
8 # Requirements:
9 # - pigz (https://zlib.net/pigz/) for using backup compression. If not available, you can use another compression algorithm (e.g. gzip)
10 #
11 # Supported database systems:
12 # - MySQL/MariaDB
13 # - PostgreSQL
14 #
15 # Usage:
16 # - With backup directory specified in the script: ./NextcloudBackup.sh
17 # - With backup directory specified by parameter: ./NextcloudBackup.sh <BackupDirectory> (e.g. ./NextcloudBackup.sh /media/hdd/nextcloud_backup)
18 #
19 # The script is based on an installation of Nextcloud using nginx and MariaDB, see https://decatec.de/home-server/nextcloud-auf-ubuntu-server-20-04-lts-mit-nginx-mariadb-php-lets-encrypt-redis-und-fail2ban/
20 #
21
22 #
23 # IMPORTANT
24 # You have to customize this script (directories, users, etc.) for your actual environment.
25 # All entries which need to be customized are tagged with "TODO".
26 #
27
28 # Make sure the script exits when any command fails
29 set -Eeuo pipefail
30
31 # Variables
32 backupMainDir=${1:-}
33
34 if [ -z "$backupMainDir" ]; then
35 # TODO: The directory where you store the Nextcloud backups (when not specified by args)
36 backupMainDir='/media/hdd/nextcloud_backup'
37 else
38 backupMainDir=$(echo $backupMainDir | sed 's:/*$::')
39 fi
40
41 currentDate=$(date +"%Y%m%d_%H%M%S")
42
43 # The actual directory of the current backup - this is a subdirectory of the main directory above with a timestamp
44 backupdir="${backupMainDir}/${currentDate}"
45
46 # TODO: Use compression for file/data dir
47 # When this is the only script for backups, it's recommend to enable compression.
48 # If the output of this script is used in another (compressing) backup (e.g. borg backup),
49 # you should probably disable compression here and only enable compression of your main backup script.
50 useCompression=true
51
52 # TOOD: The bare tar command for using compression.
53 # Use 'tar -cpzf' if you want to use gzip compression.
54 compressionCommand="tar -I pigz -cpf"
55
56 # TODO: The directory of your Nextcloud installation (this is a directory under your web root)
57 nextcloudFileDir='/var/www/nextcloud'
58
59 # TODO: The directory of your Nextcloud data directory (outside the Nextcloud file directory)
60 # If your data directory is located under Nextcloud's file directory (somewhere in the web root), the data directory should not be a separate part of the backup
61 nextcloudDataDir='/var/nextcloud_data'
62
63 # TODO: The directory of your Nextcloud's local external storage.
64 # Uncomment if you use local external storage.
65 #nextcloudLocalExternalDataDir='/var/nextcloud_external_data'
66
67 # TODO: The service name of the web server. Used to start/stop web server (e.g. 'systemctl start <webserverServiceName>')
68 webserverServiceName='nginx'
69
70 # TODO: Your web server user
71 webserverUser='www-data'
72
73 # TODO: The name of the database system (one of: mysql, mariadb, postgresql)
74 databaseSystem='mariadb'
75
76 # TODO: Your Nextcloud database name
77 nextcloudDatabase='nextcloud_db'
78
79 # TODO: Your Nextcloud database user
80 dbUser='nextcloud_db_user'
81
82 # TODO: The password of the Nextcloud database user
83 dbPassword='mYpAsSw0rd'
84
85 # TODO: The maximum number of backups to keep (when set to 0, all backups are kept)
86 maxNrOfBackups=0
87
88 # TODO: Ignore updater's backup directory in the data directory to save space
89 # Set to true to ignore the backup directory
90 ignoreUpdaterBackups=false
91
92 # File names for backup files
93 # If you prefer other file names, you'll also have to change the NextcloudRestore.sh script.
94 fileNameBackupFileDir='nextcloud-filedir.tar'
95 fileNameBackupDataDir='nextcloud-datadir.tar'
96
97 if [ "$useCompression" = true ] ; then
98 fileNameBackupFileDir='nextcloud-filedir.tar.gz'
99 fileNameBackupDataDir='nextcloud-datadir.tar.gz'
100 fi
101
102 fileNameBackupExternalDataDir=''
103
104 if [ ! -z "${nextcloudLocalExternalDataDir+x}" ] ; then
105 fileNameBackupExternalDataDir='nextcloud-external-datadir.tar'
106
107 if [ "$useCompression" = true ] ; then
108 fileNameBackupExternalDataDir='nextcloud-external-datadir.tar.gz'
109 fi
110 fi
111
112 fileNameBackupDb='nextcloud-db.sql'
113
114 # Function for error messages
115 errorecho() { cat <<< "$@" 1>&2; }
116
117 function DisableMaintenanceMode() {
118 echo "$(date +"%H:%M:%S"): Switching off maintenance mode..."
119 sudo -u "${webserverUser}" php ${nextcloudFileDir}/occ maintenance:mode --off
120 echo "Done"
121 echo
122 }
123
124 # Capture CTRL+C
125 trap CtrlC INT
126
127 function CtrlC() {
128 read -p "Backup cancelled. Keep maintenance mode? [y/n] " -n 1 -r
129 echo
130
131 if ! [[ $REPLY =~ ^[Yy]$ ]]
132 then
133 DisableMaintenanceMode
134 else
135 echo "Maintenance mode still enabled."
136 fi
137
138 echo "Starting web server..."
139 systemctl start "${webserverServiceName}"
140 echo "Done"
141 echo
142
143 exit 1
144 }
145
146 #
147 # Print information
148 #
149 echo "Backup directory: ${backupMainDir}"
150
151 #
152 # Check for root
153 #
154 if [ "$(id -u)" != "0" ]
155 then
156 errorecho "ERROR: This script has to be run as root!"
157 exit 1
158 fi
159
160 #
161 # Check if backup dir already exists
162 #
163 if [ ! -d "${backupdir}" ]
164 then
165 mkdir -p "${backupdir}"
166 else
167 errorecho "ERROR: The backup directory ${backupdir} already exists!"
168 exit 1
169 fi
170
171 #
172 # Set maintenance mode
173 #
174 echo "$(date +"%H:%M:%S"): Set maintenance mode for Nextcloud..."
175 sudo -u "${webserverUser}" php ${nextcloudFileDir}/occ maintenance:mode --on
176 echo "Done"
177 echo
178
179 #
180 # Stop web server
181 #
182 echo "$(date +"%H:%M:%S"): Stopping web server..."
183 systemctl stop "${webserverServiceName}"
184 echo "Done"
185 echo
186
187 #
188 # Backup file directory
189 #
190 echo "$(date +"%H:%M:%S"): Creating backup of Nextcloud file directory..."
191
192 if [ "$useCompression" = true ] ; then
193 `$compressionCommand "${backupdir}/${fileNameBackupFileDir}" -C "${nextcloudFileDir}" .`
194 else
195 tar -cpf "${backupdir}/${fileNameBackupFileDir}" -C "${nextcloudFileDir}" .
196 fi
197
198 echo "Done"
199 echo
200
201 #
202 # Backup data directory
203 #
204 echo "$(date +"%H:%M:%S"): Creating backup of Nextcloud data directory..."
205
206 if [ "$ignoreUpdaterBackups" = true ] ; then
207 echo "Ignoring updater backup directory"
208
209 if [ "$useCompression" = true ] ; then
210 `$compressionCommand "${backupdir}/${fileNameBackupDataDir}" --exclude="updater-*/backups/*" -C "${nextcloudDataDir}" .`
211 else
212 tar -cpf "${backupdir}/${fileNameBackupDataDir}" --exclude="updater-*/backups/*" -C "${nextcloudDataDir}" .
213 fi
214 else
215 if [ "$useCompression" = true ] ; then
216 `$compressionCommand "${backupdir}/${fileNameBackupDataDir}" -C "${nextcloudDataDir}" .`
217 else
218 tar -cpf "${backupdir}/${fileNameBackupDataDir}" -C "${nextcloudDataDir}" .
219 fi
220 fi
221
222 echo "Done"
223 echo
224
225 #
226 # Backup local external storage.
227 #
228 if [ ! -z "${nextcloudLocalExternalDataDir+x}" ] ; then
229 echo "$(date +"%H:%M:%S"): Creating backup of Nextcloud local external storage directory..."
230
231 if [ "$useCompression" = true ] ; then
232 `$compressionCommand "${backupdir}/${fileNameBackupExternalDataDir}" -C "${nextcloudLocalExternalDataDir}" .`
233 else
234 tar -cpf "${backupdir}/${fileNameBackupExternalDataDir}" -C "${nextcloudLocalExternalDataDir}" .
235 fi
236
237 echo "Done"
238 echo
239 fi
240
241 #
242 # Backup DB
243 #
244 if [ "${databaseSystem,,}" = "mysql" ] || [ "${databaseSystem,,}" = "mariadb" ]; then
245 echo "$(date +"%H:%M:%S"): Backup Nextcloud database (MySQL/MariaDB)..."
246
247 if ! [ -x "$(command -v mysqldump)" ]; then
248 errorecho "ERROR: MySQL/MariaDB not installed (command mysqldump not found)."
249 errorecho "ERROR: No backup of database possible!"
250 else
251 mysqldump --single-transaction -h localhost -u "${dbUser}" -p"${dbPassword}" "${nextcloudDatabase}" > "${backupdir}/${fileNameBackupDb}"
252 fi
253
254 echo "Done"
255 echo
256 elif [ "${databaseSystem,,}" = "postgresql" ] || [ "${databaseSystem,,}" = "pgsql" ]; then
257 echo "$(date +"%H:%M:%S"): Backup Nextcloud database (PostgreSQL)..."
258
259 if ! [ -x "$(command -v pg_dump)" ]; then
260 errorecho "ERROR: PostgreSQL not installed (command pg_dump not found)."
261 errorecho "ERROR: No backup of database possible!"
262 else
263 PGPASSWORD="${dbPassword}" pg_dump "${nextcloudDatabase}" -h localhost -U "${dbUser}" -f "${backupdir}/${fileNameBackupDb}"
264 fi
265
266 echo "Done"
267 echo
268 fi
269
270 #
271 # Start web server
272 #
273 echo "$(date +"%H:%M:%S"): Starting web server..."
274 systemctl start "${webserverServiceName}"
275 echo "Done"
276 echo
277
278 #
279 # Disable maintenance mode
280 #
281 DisableMaintenanceMode
282
283 #
284 # Delete old backups
285 #
286 if [ ${maxNrOfBackups} != 0 ]
287 then
288 nrOfBackups=$(ls -l ${backupMainDir} | grep -c ^d)
289
290 if [ ${nrOfBackups} -gt ${maxNrOfBackups} ]
291 then
292 echo "$(date +"%H:%M:%S"): Removing old backups..."
293 ls -t ${backupMainDir} | tail -$(( nrOfBackups - maxNrOfBackups )) | while read -r dirToRemove; do
294 echo "${dirToRemove}"
295 rm -r "${backupMainDir}/${dirToRemove:?}"
296 echo "Done"
297 echo
298 done
299 fi
300 fi
301
302 echo
303 echo "DONE!"
304 echo "$(date +"%H:%M:%S"): Backup created: ${backupdir}"

patrick-canterino.de