package settings import ( "dns_service/utils" "fmt" "os" "strings" ) // Helper to write file content func writeFile(path, content string) error { return os.WriteFile(path, []byte(content), 0644) } func SetSettings(new_settings map[string]any) (map[string]any, error) { // 1. Get config path and read the main dnsmasq configuration configPath := os.Getenv("DNSMASQ_CONFIG") if configPath == "" { return nil, fmt.Errorf("DNSMASQ_CONFIG environment variable not set") } data, err := os.ReadFile(configPath) if err != nil { return nil, fmt.Errorf("failed to read config file at %s: %w", configPath, err) } dnsmasqSettings := utils.DecodeSettings(string(data), "\n", "=") // 2. Update cache-size in the main config file if newCacheSize, ok := new_settings["cache_size"]; ok { oldCacheSize, oldOk := dnsmasqSettings["cache-size"] // Replace the line if it exists, otherwise dnsmasq uses a default if oldOk { newConfigContent := strings.Replace( string(data), "cache-size="+oldCacheSize, "cache-size="+fmt.Sprintf("%v", newCacheSize), 1, ) if err := writeFile(configPath, newConfigContent); err != nil { return nil, fmt.Errorf("failed to write updated config to %s: %w", configPath, err) } } } // 3. Update the resolv file if newResolvs, ok := new_settings["resolv"].([]any); ok { resolvFile, ok := dnsmasqSettings["resolv-file"] if !ok { return nil, fmt.Errorf("resolv-file path not found in dnsmasq config") } var b strings.Builder for _, v := range newResolvs { if s, ok := v.(string); ok { fmt.Fprintf(&b, "nameserver %s\n", s) } } if err := writeFile(resolvFile, b.String()); err != nil { return nil, fmt.Errorf("failed to write to resolv file %s: %w", resolvFile, err) } } // 4. Update the hosts file if newHosts, ok := new_settings["hosts"].(map[string]any); ok { hostsFile, ok := dnsmasqSettings["addn-hosts"] if !ok { return nil, fmt.Errorf("addn-hosts path not found in dnsmasq config") } var b strings.Builder for key, value := range newHosts { b.WriteString(key) switch v := value.(type) { case []any: for _, ip := range v { fmt.Fprintf(&b, " %s", ip) } b.WriteString("\n") case string: fmt.Fprintf(&b, " %s\n", v) } } if err := writeFile(hostsFile, b.String()); err != nil { return nil, fmt.Errorf("failed to write to hosts file %s: %w", hostsFile, err) } } // 5. Restart dnsmasq to apply changes if err := utils.RestartDnsmasq(); err != nil { return nil, fmt.Errorf("failed to restart dnsmasq: %w", err) } return new_settings, nil }