/
backup.go
113 lines (82 loc) · 2.68 KB
/
backup.go
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
package action
// ////////////////////////////////////////////////////////////////////////////////// //
// //
// Copyright (c) 2021 ESSENTIAL KAOS //
// Apache License, Version 2.0 <https://www.apache.org/licenses/LICENSE-2.0> //
// //
// ////////////////////////////////////////////////////////////////////////////////// //
import (
"fmt"
"hash/crc32"
"os"
"pkg.re/essentialkaos/ek.v12/fsutil"
"github.com/essentialkaos/bibop/recipe"
)
// ////////////////////////////////////////////////////////////////////////////////// //
// Backup is action processor for "backup"
func Backup(action *recipe.Action, tmpDir string) error {
path, err := action.GetS(0)
if err != nil {
return err
}
isSafePath, err := checkPathSafety(action.Command.Recipe, path)
if err != nil {
return err
}
switch {
case !isSafePath:
return fmt.Errorf("Path is unsafe (%s)", path)
case !fsutil.IsExist(path):
return fmt.Errorf("File %s does not exist", path)
case !fsutil.IsRegular(path):
return fmt.Errorf("Object %s is not a file", path)
}
pathCRC32 := calcCRC32Q(path)
err = fsutil.CopyFile(path, tmpDir+"/"+pathCRC32)
if err != nil {
return fmt.Errorf("Can't backup file: %v", err)
}
return nil
}
// BackupRestore is action processor for "backup-restore"
func BackupRestore(action *recipe.Action, tmpDir string) error {
path, err := action.GetS(0)
if err != nil {
return err
}
isSafePath, err := checkPathSafety(action.Command.Recipe, path)
if err != nil {
return err
}
pathCRC32 := calcCRC32Q(path)
backupFile := tmpDir + "/" + pathCRC32
switch {
case !isSafePath:
return fmt.Errorf("Path is unsafe (%s)", path)
case !fsutil.IsExist(backupFile):
return fmt.Errorf("Backup file for %s does not exist", path)
}
ownerUID, ownerGID, err := fsutil.GetOwner(path)
if err != nil {
return fmt.Errorf("Can't get file owner info: %v", err)
}
err = os.Remove(path)
if err != nil {
return fmt.Errorf("Can't remove original file: %v", err)
}
err = fsutil.CopyFile(backupFile, path)
if err != nil {
return fmt.Errorf("Can't copy backup file: %v", err)
}
err = os.Chown(path, ownerUID, ownerGID)
if err != nil {
return fmt.Errorf("Can't restore owner info: %v", err)
}
return nil
}
// ////////////////////////////////////////////////////////////////////////////////// //
// calcCRC32Q calculate CRC32 checksum
func calcCRC32Q(data string) string {
table := crc32.MakeTable(0xD5828281)
return fmt.Sprintf("%08x", crc32.Checksum([]byte(data), table))
}