blob: dffdfbef550c2b01eb56883e3f5cd64de9e7c9e7 [file] [log] [blame]
Giorgi Lekveishvili46743d42023-12-10 15:47:23 +04001package tasks
2
3import (
4 "bytes"
5 "embed"
6 "encoding/base64"
7 "fmt"
8 "path"
9 "strings"
10 "text/template"
gio3af43942024-04-16 08:13:50 +040011
12 "github.com/giolekva/pcloud/core/installer"
Giorgi Lekveishvili46743d42023-12-10 15:47:23 +040013)
14
15//go:embed env-tmpl
16var filesTmpls embed.FS
17
Giorgi Lekveishvili46743d42023-12-10 15:47:23 +040018func NewActivateEnvTask(env Env, st *state) Task {
Giorgi Lekveishvili378ea882023-12-12 13:59:18 +040019 return newSequentialParentTask(
Giorgi Lekveishvili5c1b06e2024-03-28 15:19:44 +040020 "Activate GitOps",
21 false,
Giorgi Lekveishvili378ea882023-12-12 13:59:18 +040022 AddNewEnvTask(env, st),
23 // TODO(gio): sync dodo-flux
24 )
25}
26
27func AddNewEnvTask(env Env, st *state) Task {
28 t := newLeafTask("Commit initial configuration", func() error {
Giorgi Lekveishvili77ee2dc2023-12-11 16:51:10 +040029 ssPublicKeys, err := st.ssClient.GetPublicKeys()
Giorgi Lekveishvili46743d42023-12-10 15:47:23 +040030 if err != nil {
31 return err
32 }
Giorgi Lekveishvili77ee2dc2023-12-11 16:51:10 +040033 repoHost := strings.Split(st.ssClient.Addr, ":")[0]
gio3af43942024-04-16 08:13:50 +040034 return st.repo.Atomic(func(r installer.RepoFS) (string, error) {
35 kust, err := installer.ReadKustomization(r, "environments/kustomization.yaml")
Giorgi Lekveishvili77ee2dc2023-12-11 16:51:10 +040036 if err != nil {
gio3af43942024-04-16 08:13:50 +040037 return "", err
Giorgi Lekveishvili77ee2dc2023-12-11 16:51:10 +040038 }
gio3af43942024-04-16 08:13:50 +040039 kust.AddResources(env.Name)
40 tmpls, err := template.ParseFS(filesTmpls, "env-tmpl/*.yaml")
41 if err != nil {
42 return "", err
Giorgi Lekveishvili77ee2dc2023-12-11 16:51:10 +040043 }
gio3af43942024-04-16 08:13:50 +040044 var knownHosts bytes.Buffer
45 for _, key := range ssPublicKeys {
46 fmt.Fprintf(&knownHosts, "%s %s\n", repoHost, key)
47 }
48 for _, tmpl := range tmpls.Templates() { // TODO(gio): migrate to cue
49 dstPath := path.Join("environments", env.Name, tmpl.Name())
50 dst, err := r.Writer(dstPath)
51 if err != nil {
52 return "", err
53 }
54 defer dst.Close()
55 if err := tmpl.Execute(dst, map[string]string{
56 "Name": env.Name,
57 "PrivateKey": base64.StdEncoding.EncodeToString(st.keys.RawPrivateKey()),
58 "PublicKey": base64.StdEncoding.EncodeToString(st.keys.RawAuthorizedKey()),
59 "RepoHost": repoHost,
60 "RepoName": "config",
61 "KnownHosts": base64.StdEncoding.EncodeToString(knownHosts.Bytes()),
62 }); err != nil {
63 return "", err
64 }
65 }
66 if err := installer.WriteYaml(r, "environments/kustomization.yaml", kust); err != nil {
67 return "", err
68 }
69 return fmt.Sprintf("%s: initialize environment", env.Name), nil
70 })
Giorgi Lekveishvili77ee2dc2023-12-11 16:51:10 +040071 })
72 return &t
Giorgi Lekveishvili46743d42023-12-10 15:47:23 +040073}