-
Notifications
You must be signed in to change notification settings - Fork 9
/
backup.go
91 lines (76 loc) · 1.76 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
package crypto
import (
"fmt"
"os"
"path/filepath"
"github.com/pluralsh/plural-cli/pkg/api"
"github.com/pluralsh/plural-cli/pkg/utils"
"github.com/pluralsh/plural-cli/pkg/utils/git"
"github.com/pluralsh/plural-cli/pkg/utils/pathing"
)
func BackupKey(client api.Client) error {
p := getKeyPath()
aes, err := Read(p)
if err != nil {
return err
}
host, _ := os.Hostname()
name, err := utils.ReadLineDefault("Give your key backup a name", host)
if err != nil {
return err
}
repos := []string{}
if repo, err := git.GetURL(); err == nil {
repos = append(repos, repo)
}
utils.Highlight("===> backing up aes key to plural\n")
return client.CreateKeyBackup(api.KeyBackupAttributes{
Name: name,
Repositories: repos,
Key: aes.Key,
})
}
func DownloadBackup(client api.Client, name string) error {
backup, err := client.GetKeyBackup(name)
if err != nil {
return api.GetErrorResponse(err, "GetKeyBackup")
}
if backup == nil {
return fmt.Errorf("no backup found for %s", name)
}
return Setup(backup.Value)
}
func backupKey(key string) error {
p := getKeyPath()
if utils.Exists(p) {
aes, err := Read(p)
if err != nil {
return err
}
if aes != nil && aes.Key == key {
return nil
}
ind := 0
for {
bp := backupPath(ind)
if utils.Exists(bp) {
ind++
continue
}
utils.Highlight("===> backing up aes key to %s\n", bp)
if err := os.MkdirAll(filepath.Dir(bp), os.ModePerm); err != nil {
return err
}
return utils.CopyFile(p, bp)
}
}
return nil
}
func backupPath(ind int) string {
folder, _ := os.UserHomeDir()
infix := ""
if ind > 0 {
infix = fmt.Sprintf("_%d.", ind)
}
return pathing.SanitizeFilepath(filepath.Join(folder, ".plural", "keybackups", fmt.Sprintf("key_backup%s", infix)))
}