From df2003023a81fe6e8fd500f0ce569d3323a96f77 Mon Sep 17 00:00:00 2001
From: Kjeld Schouten <info@kjeldschouten.nl>
Date: Fri, 8 Nov 2024 00:39:24 +0100
Subject: [PATCH] fix(clustertool): fix kubectl logging error, add kubeconfig
 command and fix some command docs

---
 clustertool/cmd/adv_testcmd.go      | 20 ++++++++++-
 clustertool/cmd/talos_bootstrap.go  |  2 +-
 clustertool/cmd/talos_health.go     |  6 +++-
 clustertool/cmd/talos_kubeconfig.go | 52 +++++++++++++++++++++++++++++
 clustertool/cmd/talos_reset.go      |  6 +++-
 clustertool/cmd/talos_upgrade.go    |  6 +++-
 clustertool/go.mod                  |  1 +
 clustertool/go.sum                  |  2 ++
 clustertool/main.go                 | 11 ++++++
 9 files changed, 101 insertions(+), 5 deletions(-)
 create mode 100644 clustertool/cmd/talos_kubeconfig.go

diff --git a/clustertool/cmd/adv_testcmd.go b/clustertool/cmd/adv_testcmd.go
index 422c76ebe6a2b..6063166457491 100644
--- a/clustertool/cmd/adv_testcmd.go
+++ b/clustertool/cmd/adv_testcmd.go
@@ -1,10 +1,16 @@
 package cmd
 
 import (
+    "context"
+    "os"
+    "path/filepath"
     "strings"
 
+    "github.com/rs/zerolog/log"
     "github.com/spf13/cobra"
+    "github.com/truecharts/public/clustertool/pkg/helper"
     "github.com/truecharts/public/clustertool/pkg/initfiles"
+    "github.com/truecharts/public/clustertool/pkg/kubectlcmds"
     "github.com/truecharts/public/clustertool/pkg/talassist"
 )
 
@@ -17,13 +23,25 @@ var testcmd = &cobra.Command{
     Short: "tests specific code for developer usages",
     Long:  advTestCmdlongHelp,
     Run: func(cmd *cobra.Command, args []string) {
+        ctx := context.Background()
         initfiles.LoadTalEnv(false)
         talassist.LoadTalConfig()
         // err := fluxhandler.ProcessJSONFiles("./testdata/truenas_exports")
         // if err != nil {
         //  log.Info().Msg("Error:", err)
         // }
-        RunApply(false, "", []string{})
+        var manifestPaths = []string{
+            filepath.Join(helper.KubernetesPath, "flux-system", "flux", "sopssecret.secret.yaml"),
+            filepath.Join(helper.KubernetesPath, "flux-system", "flux", "deploykey.secret.yaml"),
+            filepath.Join(helper.KubernetesPath, "flux-system", "flux", "clustersettings.secret.yaml"),
+        }
+        for _, filePath := range manifestPaths {
+            log.Info().Msgf("Bootstrap: Loading Manifest: %v", filePath)
+            if err := kubectlcmds.KubectlApply(ctx, filePath); err != nil {
+                log.Info().Msgf("Error applying manifest for %s: %v\n", filepath.Base(filePath), err)
+                os.Exit(1)
+            }
+        }
     },
 }
 
diff --git a/clustertool/cmd/talos_bootstrap.go b/clustertool/cmd/talos_bootstrap.go
index ef1d82d90548c..ca7ba992c7613 100644
--- a/clustertool/cmd/talos_bootstrap.go
+++ b/clustertool/cmd/talos_bootstrap.go
@@ -17,7 +17,7 @@ var advBootstrapLongHelp = strings.TrimSpace(`
 var bootstrap = &cobra.Command{
     Use:     "bootstrap",
     Short:   "bootstrap first Talos Node",
-    Example: "clustertool adv bootstrap",
+    Example: "clustertool talos bootstrap",
     Long:    advBootstrapLongHelp,
     Run:     bootstrapfunc,
 }
diff --git a/clustertool/cmd/talos_health.go b/clustertool/cmd/talos_health.go
index f2f3ee330ddcb..91bf17b20a9d8 100644
--- a/clustertool/cmd/talos_health.go
+++ b/clustertool/cmd/talos_health.go
@@ -7,7 +7,9 @@ import (
     "github.com/spf13/cobra"
     "github.com/truecharts/public/clustertool/pkg/gencmd"
     "github.com/truecharts/public/clustertool/pkg/helper"
+    "github.com/truecharts/public/clustertool/pkg/initfiles"
     "github.com/truecharts/public/clustertool/pkg/sops"
+    "github.com/truecharts/public/clustertool/pkg/talassist"
 )
 
 var advHealthLongHelp = strings.TrimSpace(`
@@ -17,12 +19,14 @@ var advHealthLongHelp = strings.TrimSpace(`
 var health = &cobra.Command{
     Use:     "health",
     Short:   "Check Talos Cluster Health",
-    Example: "clustertool adv health",
+    Example: "clustertool talos health",
     Long:    advHealthLongHelp,
     Run: func(cmd *cobra.Command, args []string) {
         if err := sops.DecryptFiles(); err != nil {
             log.Info().Msgf("Error decrypting files: %v\n", err)
         }
+        initfiles.LoadTalEnv(false)
+        talassist.LoadTalConfig()
         log.Info().Msg("Running Cluster HealthCheck")
         healthcmd := gencmd.GenPlain("health", helper.TalEnv["VIP_IP"], []string{})
         gencmd.ExecCmd(healthcmd[0])
diff --git a/clustertool/cmd/talos_kubeconfig.go b/clustertool/cmd/talos_kubeconfig.go
new file mode 100644
index 0000000000000..7d62e6619976d
--- /dev/null
+++ b/clustertool/cmd/talos_kubeconfig.go
@@ -0,0 +1,52 @@
+package cmd
+
+import (
+    "strings"
+
+    "github.com/rs/zerolog/log"
+    "github.com/spf13/cobra"
+    "github.com/truecharts/public/clustertool/pkg/gencmd"
+    "github.com/truecharts/public/clustertool/pkg/initfiles"
+    "github.com/truecharts/public/clustertool/pkg/sops"
+    "github.com/truecharts/public/clustertool/pkg/talassist"
+)
+
+var advKubeconfigLongHelp = strings.TrimSpace(`
+
+`)
+
+var kubeconfig = &cobra.Command{
+    Use:     "kubeconfig",
+    Short:   "kubeconfig for Talos Cluster",
+    Example: "clustertool talos kubeconfig <NodeIP>",
+    Long:    advResetLongHelp,
+    Run: func(cmd *cobra.Command, args []string) {
+        var extraArgs []string
+        node := ""
+
+        if len(args) > 1 {
+            extraArgs = args[1:]
+        }
+        if len(args) >= 1 {
+            node = args[0]
+            if args[0] == "all" {
+                node = ""
+            }
+        }
+
+        if err := sops.DecryptFiles(); err != nil {
+            log.Info().Msgf("Error decrypting files: %v\n", err)
+        }
+        initfiles.LoadTalEnv(false)
+        talassist.LoadTalConfig()
+        log.Info().Msg("Running Cluster kubeconfig")
+
+        taloscmds := gencmd.GenPlain("kubeconfig", node, extraArgs)
+        gencmd.ExecCmds(taloscmds, true)
+
+    },
+}
+
+func init() {
+    talosCmd.AddCommand(kubeconfig)
+}
diff --git a/clustertool/cmd/talos_reset.go b/clustertool/cmd/talos_reset.go
index bcf9c6eae0dd7..40cdbc5d7f2b3 100644
--- a/clustertool/cmd/talos_reset.go
+++ b/clustertool/cmd/talos_reset.go
@@ -6,7 +6,9 @@ import (
     "github.com/rs/zerolog/log"
     "github.com/spf13/cobra"
     "github.com/truecharts/public/clustertool/pkg/gencmd"
+    "github.com/truecharts/public/clustertool/pkg/initfiles"
     "github.com/truecharts/public/clustertool/pkg/sops"
+    "github.com/truecharts/public/clustertool/pkg/talassist"
 )
 
 var advResetLongHelp = strings.TrimSpace(`
@@ -16,7 +18,7 @@ var advResetLongHelp = strings.TrimSpace(`
 var reset = &cobra.Command{
     Use:     "reset",
     Short:   "Reset Talos Nodes and Kubernetes",
-    Example: "clustertool adv reset <NodeIP>",
+    Example: "clustertool talos reset <NodeIP>",
     Long:    advResetLongHelp,
     Run: func(cmd *cobra.Command, args []string) {
         var extraArgs []string
@@ -35,6 +37,8 @@ var reset = &cobra.Command{
         if err := sops.DecryptFiles(); err != nil {
             log.Info().Msgf("Error decrypting files: %v\n", err)
         }
+        initfiles.LoadTalEnv(false)
+        talassist.LoadTalConfig()
 
         log.Info().Msg("Running Cluster node Reset")
 
diff --git a/clustertool/cmd/talos_upgrade.go b/clustertool/cmd/talos_upgrade.go
index 86f11fb251d80..9a30c700289cf 100644
--- a/clustertool/cmd/talos_upgrade.go
+++ b/clustertool/cmd/talos_upgrade.go
@@ -7,7 +7,9 @@ import (
     "github.com/spf13/cobra"
     "github.com/truecharts/public/clustertool/pkg/gencmd"
     "github.com/truecharts/public/clustertool/pkg/helper"
+    "github.com/truecharts/public/clustertool/pkg/initfiles"
     "github.com/truecharts/public/clustertool/pkg/sops"
+    "github.com/truecharts/public/clustertool/pkg/talassist"
 )
 
 var upgradeLongHelp = strings.TrimSpace(`
@@ -21,7 +23,7 @@ On top of this, after upgrading Talos on all nodes, it also executes kubernetes-
 var upgrade = &cobra.Command{
     Use:     "upgrade",
     Short:   "Upgrade Talos Nodes and Kubernetes",
-    Example: "clustertool upgrade <NodeIP>",
+    Example: "clustertool talos upgrade <NodeIP>",
     Long:    upgradeLongHelp,
     Run: func(cmd *cobra.Command, args []string) {
         var extraArgs []string
@@ -40,6 +42,8 @@ var upgrade = &cobra.Command{
         if err := sops.DecryptFiles(); err != nil {
             log.Info().Msgf("Error decrypting files: %v\n", err)
         }
+        initfiles.LoadTalEnv(false)
+        talassist.LoadTalConfig()
 
         log.Info().Msg("Running Cluster Upgrade")
 
diff --git a/clustertool/go.mod b/clustertool/go.mod
index 19fe1f52bc18c..639ac275282f6 100644
--- a/clustertool/go.mod
+++ b/clustertool/go.mod
@@ -9,6 +9,7 @@ require (
     github.com/budimanjojo/talhelper/v3 v3.0.8
     github.com/getsops/sops/v3 v3.9.1
     github.com/go-git/go-git/v5 v5.12.0
+    github.com/go-logr/zerologr v1.2.3
     github.com/go-playground/validator/v10 v10.22.1
     github.com/invopop/jsonschema v0.12.0
     github.com/joho/godotenv v1.5.1
diff --git a/clustertool/go.sum b/clustertool/go.sum
index 7b5d2b8cda32e..353bc6780c5f9 100644
--- a/clustertool/go.sum
+++ b/clustertool/go.sum
@@ -277,6 +277,8 @@ github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
 github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
 github.com/go-logr/zapr v1.3.0 h1:XGdV8XW8zdwFiwOA2Dryh1gj2KRQyOOoNmBy4EplIcQ=
 github.com/go-logr/zapr v1.3.0/go.mod h1:YKepepNBd1u/oyhd/yQmtjVXmm9uML4IXUgMOwR8/Gg=
+github.com/go-logr/zerologr v1.2.3 h1:up5N9vcH9Xck3jJkXzgyOxozT14R47IyDODz8LM1KSs=
+github.com/go-logr/zerologr v1.2.3/go.mod h1:BxwGo7y5zgSHYR1BjbnHPyF/5ZjVKfKxAZANVu6E8Ho=
 github.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ=
 github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY=
 github.com/go-openapi/jsonreference v0.21.0 h1:Rs+Y7hSXT83Jacb7kFyjn4ijOuVGSvOdF2+tg1TRrwQ=
diff --git a/clustertool/main.go b/clustertool/main.go
index 1e40441888857..83c16a0a4b787 100644
--- a/clustertool/main.go
+++ b/clustertool/main.go
@@ -8,9 +8,11 @@ import (
     "github.com/rs/zerolog"
     "github.com/rs/zerolog/log"
 
+    "github.com/go-logr/zerologr"
     "github.com/truecharts/public/clustertool/cmd"
     "github.com/truecharts/public/clustertool/embed"
     "github.com/truecharts/public/clustertool/pkg/helper"
+    k8slog "sigs.k8s.io/controller-runtime/pkg/log"
 )
 
 var Version = "dev"
@@ -54,6 +56,15 @@ func main() {
         NoColor:    noColor,      // Set to true if you prefer no color
     })
 
+    // Initialize zerolog with console output
+    zlogger := zerolog.New(os.Stderr).With().Timestamp().Logger()
+
+    // Wrap zerolog with zerologr to create a logr.Logger
+    logger := zerologr.New(&zlogger)
+
+    // Set this logger for dependencies expecting log.SetLogger
+    k8slog.SetLogger(logger)
+
     fmt.Printf("\n%s\n", helper.Logo)
     fmt.Printf("---\nClustertool Version: %s\n---\n", Version)