/
certs_upload.go
95 lines (84 loc) · 2.28 KB
/
certs_upload.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
package commands
import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"os/signal"
"text/tabwriter"
"github.com/reddec/syno-cli/pkg/client"
)
//nolint:staticcheck
type CertsUpload struct {
SynoClient `group:"Synology Client" namespace:"synology" env-namespace:"SYNOLOGY"`
Key string `short:"k" long:"key" env:"KEY" description:"Path to private key. Use - (dash) to read it from stdin" default:"-"`
Cert string `short:"c" long:"cert" env:"CERT" description:"Path to server certificate" required:"true"`
CA string `short:"C" long:"ca" env:"CA" description:"Path to intermediate certificate"`
Format string `short:"f" long:"format" env:"FORMAT" description:"Output format" default:"table" choice:"table" choice:"json"`
Default bool `short:"d" long:"default" env:"DEFAULT" description:"Set certificate as default"`
Args struct {
Name string `positional-arg-name:"name" env:"NAME" description:"certificate name" required:"true"`
} `positional-args:"true"`
}
func (lc *CertsUpload) Execute([]string) error {
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, os.Kill)
defer cancel()
syno := lc.Client()
var privateFile io.ReadCloser
if lc.Key == "-" {
privateFile = os.Stdin
} else if f, err := os.Open(lc.Key); err == nil {
privateFile = f
} else {
return err
}
defer privateFile.Close()
certFile, err := os.Open(lc.Cert)
if err != nil {
return err
}
defer certFile.Close()
var caFile io.Reader
if lc.CA != "" {
f, err := os.Open(lc.CA)
if err != nil {
return err
}
caFile = f
defer f.Close()
}
info, err := syno.UploadCert(ctx, client.NewCertificate{
Name: lc.Args.Name,
AsDefault: false,
Cert: certFile,
CA: caFile,
Key: privateFile,
})
if err != nil {
return err
}
return lc.show(info)
}
//nolint:gomnd
func (lc *CertsUpload) show(info *client.CertUploadResult) error {
switch lc.Format {
case fmtJSON:
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
return enc.Encode(info)
case fmtTable:
fallthrough
default:
tw := tabwriter.NewWriter(os.Stdout, 3, 4, 2, ' ', 0)
_, _ = fmt.Fprintln(tw,
"ID", "\t",
"Server restarted", "\t",
)
_, _ = fmt.Fprintln(tw,
info.CertificateID, "\t",
info.ServerRestarted, "\t",
)
return tw.Flush()
}
}