forked from TheBestPessimist/duplicacy-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backup.ps1
362 lines (284 loc) · 10.8 KB
/
backup.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
# ================================================
#
# The log folder is created in the folder .duplicacy/tbp-logs/
#
# If the user wishes (sets the flag to true) and the script is run as an Administrator,
# the backup command will use the -vss flag (Shadow Copy),
# which can only be used as an Administrator.
#
# Thanks to <bassebaba/DuplicacyPowershell> for the initial script which
# inspired this one and from which I borrowed some parts.
#
# The script can be run manually (after setting the correct paths and variable names) like this:
# powershell -NoProfile -ExecutionPolicy Bypass -File "C:\duplicacy repo\backup.ps1" -Verb RunAs;
#
#
# ================================================
# ================================================
# Import the global and local config files
. "$PSScriptRoot\default_config.ps1"
. "$PSScriptRoot\user_config.ps1"
# ================================================
# ================================================
# ================================================
# Various timers keeping time
#
$timings = @{
scriptStartTime = 0
scriptEndTime = 0
scriptTotalRuntime = 0
}
# ================================================
# ================================================
# Info about the logging
$log = @{
basePath = ".duplicacy/tbp-logs" # relative to $repositoryFolder
folder = $( Get-Date ).toString("yyyy-MM-dd dddd")
fileName = "backup-log " + $( Get-Date ).toString("yyyy-MM-dd HH-mm-ss") + "_" + $( Get-Date ).Ticks + ".log"
}
$log.workingPath = $log.basePath + "/" + $log.folder + "/"
$log.filePath = $log.workingPath + $log.fileName
# ================================================
# ================================================
# Duplicacy global options
$duplicacyOptions_temp = " -log "
if ($duplicacyDebug)
{
$duplicacyOptions_temp += " -d "
}
# ================================================
# Duplicacy backup options
$duplicacyBackupOptions_temp = ""
if ($duplicacyVssOption -And ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]"Administrator"))
{
$duplicacyBackupOptions_temp += " -vss "
$duplicacyBackupOptions_temp += " -vss-timeout " + $duplicacyVssTimeout
}
if ($duplicacyMaxUploadRate)
{
$duplicacyBackupOptions_temp += " -limit-rate " + $duplicacyMaxUploadRate
}
# ================================================
# Duplicacy prune options
#
$duplicacyPruneOptions_temp = $duplicacyPruneRetentionPolicy
$duplicacyPruneOptionsOffsite_temp = $duplicacyPruneRetentionPolicy
if ($duplicacyPruneNumberOfThreads)
{
$duplicacyPruneOptions_temp += " -threads " + $duplicacyPruneNumberOfThreads
$duplicacyPruneOptionsOffsite_temp += " -threads " + $duplicacyPruneNumberOfThreads
}
if ($duplicacyPruneExtraOptionsLocal)
{
$duplicacyPruneOptions_temp += " $duplicacyPruneExtraOptionsLocal "
}
if ($duplicacyPruneExtraOptionsOffsite)
{
$duplicacyPruneOptionsOffsite_temp += " $duplicacyPruneExtraOptionsOffsite "
}
# ================================================
# Duplicacy copy options
$duplicacyCopyOptions_temp = ""
if ($duplicacyCopyNumberOfThreads)
{
$duplicacyCopyOptions_temp += " -threads " + $duplicacyCopyNumberOfThreads
}
if ($duplicacyMaxCopyRate)
{
$duplicacyCopyOptions_temp += " -upload-limit-rate " + $duplicacyMaxCopyRate
}
# ================================================
# ================================================
# Create the commands in a hash table
$duplicacy = @{
exe = " $duplicacyExePath "
options = " $duplicacyOptions_temp "
command = " $duplicacyExePath $duplicacyOptions_temp "
backup = " backup -stats $duplicacyBackupOptions_temp "
list = " list "
check = " check "
prune = " prune $duplicacyPruneOptions_temp "
pruneOffsite = " prune $duplicacyPruneOptionsOffsite_temp "
copy = " copy -to offsite $duplicacyCopyOptions_temp "
}
# ================================================
function main
{
# http://www.wallacetech.co.uk/?p=693
doPreBackupTasks
# ================================================
# ================================================
# ===================================================
# ===== Execute the commands. Select which ones =====
doDuplicacyCommand $duplicacy.backup
# doDuplicacyCommand $duplicacy.list
# doDuplicacyCommand $duplicacy.check
# doDuplicacyCommand $duplicacy.copy
# doDuplicacyCommand $duplicacy.prune
# doDuplicacyCommand $duplicacy.pruneOffsite
# ================================================
# ================================================
doPostBackupTasks
}
# ================================================
# Helper functions
#
function doPreBackupTasks()
{
Push-Location $repositoryFolder
if (!(Test-Path -Path $log.workingPath))
{
New-Item -ItemType directory -Path $log.workingPath
log "Folder ${log.workingPath} does not exist. It has just been created"
}
logStartBackupProcess
zipOlderLogFiles
}
function logStartBackupProcess()
{
$timings.scriptStartTime = Get-Date
$startTime = $timings.scriptStartTime.ToString("yyyy-MM-dd HH:mm:ss")
log
log
log "================================================================="
log "==== Starting Duplicacy backup process =========================="
log "======"
log "====== Start time is: $startTime"
log ("====== logFile is: " + (Resolve-Path -Path $log.filePath).Path)
log "================================================================="
}
function zipOlderLogFiles()
{
$logFiles = Get-ChildItem $log.basePath -Directory | Where-Object { $_.LastWriteTime -lt (Get-Date -Hour 0 -Minute 0 -Second 1) }
foreach ($folder in $logFiles)
{
$fullName = $folder.FullName
$zipFileName = "$fullName.zip"
log "Zipping (and then deleting) the folder: $fullName to the zipFile: $zipFileName"
Compress-Archive -Path $fullName -DestinationPath $zipFileName -CompressionLevel Optimal -Update
# Remove-Item -Path $fullName # not good since it deletes the Folder. I want to send it to recycle bin.
$shell = New-Object -ComObject "Shell.Application"
$item = $shell.Namespace(0).ParseName("$fullName")
$item.InvokeVerb("delete")
}
}
function doPostBackupTasks()
{
logFinishBackupProcess
if ($enableSlackNotifications)
{
createSlackMessage
}
Pop-Location
}
function logFinishBackupProcess()
{
$timings.scriptEndTime = Get-Date
$timings.scriptTotalRuntime = New-Timespan -Start $timings.scriptStartTime -End $timings.scriptEndTime
$startTime = $timings.scriptStartTime.ToString("yyyy-MM-dd HH:mm:ss")
$endTime = $timings.scriptEndTime.ToString("yyyy-MM-dd HH:mm:ss")
log "================================================================="
log "==== Finished Duplicacy backup process =========================="
log "======"
log ("====== Total runtime: {0} Days {1} Hours {2} Minutes {3} Seconds, start time: {4}, finish time: {5}" -f $timings.scriptTotalRuntime.Days, $timings.scriptTotalRuntime.Hours, $timings.scriptTotalRuntime.Minutes, $timings.scriptTotalRuntime.Seconds, $startTime, $endTime)
log ("====== logFile is: " + (Resolve-Path -Path $log.filePath).Path)
log "================================================================="
}
# function to split the lines at the end of the log file into individual slack notifications
function createSlackMessage()
{
$slackOut = Get-Content -Tail $logLinestoSlack -Path $log.filePath
$slackMessage = "*** DUPLICACY BACKUP PROCESS COMPLETE ***`n" + "-- " + "$( $slackOut -join "`n -- " )"
slackNotify($slackMessage)
}
function slackNotify($notify_text)
{
$payload = @{
"text" = $notify_text
}
Invoke-WebRequest `
-Body (ConvertTo-Json -Compress -InputObject $payload) `
-Method Post `
-Uri "$slackWebhookURL" | Out-Null
}
function doDuplicacyCommand($arg)
{
$command = $duplicacy.command + $arg
log "==="
log "=== Now executting $command"
log "==="
invoke $command
}
function invoke($command)
{
Invoke-Expression $command | Tee-Object -FilePath "$( $log.filePath )" -Append
}
function log($str)
{
$date = $( Get-Date ).ToString("yyyy-MM-dd HH:mm:ss.fff")
invoke " Write-Output '${date} $str' "
}
function elevateAsAdmin()
{
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]"Administrator"))
{
Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs; exit
}
}
# elevateAsAdmin
main
# Read-Host "Press ENTER to exit: "
# # Config / Global vars
# $duplicacyMasterDir="C:\duplicacy repo" # Logfiles will go here, subdir /Logs
# $repoLocations=@("C:\duplicacy repo") # All repos to backup
# $duplicacyExe="C:\duplicacy repo\z.exe" # Path to .exe
# $duplicacyGlobalOptions="-d -log" # Global options to add to duplicacy commands
# $backupCmd="backup -stats -threads 20" # Backup command. TODO: Needs improvement, we should use some sort of backup-class instead to have per-repo specifics here...
# #$backupCmd="list"
# # Pushover, leave empty for none
# $sendPushoverOnSuccess=$false
# $pushoverUserKey=""
# $pushoverToken=""
# # Main
# function main {
# $msg = ""
# foreach($repo in $repoLocations){
# log ""
# logDivider "Repo: $repo"
# cd $repo
# log "Running Duplicacy backup ..."
# Invoke-Expression "& '$duplicacyExe' $duplicacyGlobalOptions $backupCmd" | Tee-Object -Variable dupOut
# if($lastexitcode){
# throw "Duplicacy non zero exit code"
# }
# logDivider "Done backing up: $repo"
# $stats = logStats $dupOut
# $msg += "$repo :: $stats `n"
# }
# if($sendPushoverOnSuccess){
# sendPushover "Backup success" $msg
# }
# }
# function logStats($dupOutput) {
# try {
# $backupStats = $dupOutput.Split("`n") | Select-String -Pattern 'All chunks'
# $match = ([regex]::Match($backupStats,'(.*)total, (.*) bytes; (.*) new, (.*) bytes, (.*) bytes'))
# $tot = formatData $match.Groups[2].Value
# $new = formatData $match.Groups[4].Value
# $upload = formatData $match.Groups[5].Value
# return "$tot, $new -> upload $upload"
# } Catch {
# return "Could not parse stats"
# }
# }
# function formatData($str){
# $last = $str[-1]
# $foo = ($str -replace ".$")/1000
# $bar = [int]$foo
# if($last -eq "K"){
# return "$bar MB"
# } elseif ($last -eq "M"){
# return "$bar GB"
# }
# return $str
# }