116 lines
2.6 KiB
Go
116 lines
2.6 KiB
Go
package internal
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/spf13/cobra"
|
|
"k8s.io/klog/v2"
|
|
|
|
"example.com/monok8s/pkg/system"
|
|
)
|
|
|
|
const defaultFWEnvConfigPath = "/host/etc/fw_env.config"
|
|
|
|
func newInternalFWSetEnvCmd() *cobra.Command {
|
|
var key string
|
|
var value string
|
|
var configPath string
|
|
|
|
cmd := &cobra.Command{
|
|
Use: "fw-setenv",
|
|
Short: "Run fw_setenv",
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
ctx := cmd.Context()
|
|
|
|
key = strings.TrimSpace(key)
|
|
value = strings.TrimSpace(value)
|
|
configPath = strings.TrimSpace(configPath)
|
|
|
|
if key == "" {
|
|
return fmt.Errorf("--key is required")
|
|
}
|
|
if value == "" {
|
|
return fmt.Errorf("--value is required")
|
|
}
|
|
if configPath == "" {
|
|
configPath = defaultFWEnvConfigPath
|
|
}
|
|
|
|
if _, err := os.Stat(configPath); err != nil {
|
|
return fmt.Errorf("stat fw env config %q: %w", configPath, err)
|
|
}
|
|
|
|
runner := system.NewRunner(system.RunnerConfig{
|
|
DefaultTimeout: 15 * time.Second,
|
|
StreamOutput: false,
|
|
Logger: &system.StdLogger{},
|
|
})
|
|
|
|
// Preflight first so failure is clearer than blindly writing.
|
|
preflightRes, err := runner.RunWithOptions(
|
|
ctx,
|
|
"fw_printenv",
|
|
[]string{"-c", configPath},
|
|
system.RunOptions{
|
|
Quiet: true,
|
|
},
|
|
)
|
|
if err != nil {
|
|
if preflightRes != nil {
|
|
klog.ErrorS(err, "fw_printenv preflight failed",
|
|
"stdout", strings.TrimSpace(preflightRes.Stdout),
|
|
"stderr", strings.TrimSpace(preflightRes.Stderr),
|
|
)
|
|
}
|
|
return fmt.Errorf("fw_printenv preflight: %w", err)
|
|
}
|
|
|
|
res, err := runner.RunWithOptions(
|
|
ctx,
|
|
"fw_setenv",
|
|
[]string{
|
|
"-c", configPath,
|
|
key, value,
|
|
},
|
|
system.RunOptions{
|
|
Quiet: true,
|
|
},
|
|
)
|
|
if err != nil {
|
|
if res != nil {
|
|
klog.ErrorS(err, "fw_setenv failed",
|
|
"key", key,
|
|
"value", value,
|
|
"stdout", strings.TrimSpace(res.Stdout),
|
|
"stderr", strings.TrimSpace(res.Stderr),
|
|
)
|
|
}
|
|
return err
|
|
}
|
|
|
|
if strings.TrimSpace(res.Stdout) != "" {
|
|
klog.InfoS("fw_setenv stdout", "output", strings.TrimSpace(res.Stdout))
|
|
}
|
|
if strings.TrimSpace(res.Stderr) != "" {
|
|
klog.InfoS("fw_setenv stderr", "output", strings.TrimSpace(res.Stderr))
|
|
}
|
|
|
|
klog.InfoS("fw_setenv succeeded",
|
|
"key", key,
|
|
"value", value,
|
|
"configPath", configPath,
|
|
)
|
|
return nil
|
|
},
|
|
}
|
|
|
|
cmd.Flags().StringVar(&key, "key", "", "U-Boot environment variable name")
|
|
cmd.Flags().StringVar(&value, "value", "", "U-Boot environment variable value")
|
|
cmd.Flags().StringVar(&configPath, "config", defaultFWEnvConfigPath, "Path to fw_env.config")
|
|
|
|
return cmd
|
|
}
|