Search/init.go
2024-08-08 15:03:33 +02:00

211 lines
4.2 KiB
Go

package main
import (
"bufio"
"crypto/rand"
"encoding/base64"
"fmt"
"log"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/fsnotify/fsnotify"
"gopkg.in/ini.v1"
)
type Config struct {
Port int
AuthCode string
Peers []string
PeerID string
Domain string
}
var defaultConfig = Config{
Port: 5000,
Domain: "localhost",
}
const configFilePath = "config.ini"
var config Config
var configLock sync.RWMutex
func main() {
err := initConfig()
if err != nil {
fmt.Println("Error during initialization:", err)
return
}
loadNodeConfig()
go startFileWatcher()
go checkMasterHeartbeat()
if config.AuthCode == "" {
config.AuthCode = generateStrongRandomString(64)
fmt.Printf("Generated connection code: %s\n", config.AuthCode)
saveConfig(config)
}
// Generate Host ID
hostID, nodeErr := generateHostID()
if nodeErr != nil {
log.Fatalf("Failed to generate host ID: %v", nodeErr)
}
config.PeerID = hostID
if len(config.Peers) > 0 {
time.Sleep(2 * time.Second) // Give some time for connections to establish
startElection()
}
go startNodeClient()
runServer()
}
func initConfig() error {
if _, err := os.Stat(configFilePath); os.IsNotExist(err) {
return createConfig()
}
fmt.Println("Configuration file already exists.")
config = loadConfig()
return nil
}
func createConfig() error {
reader := bufio.NewReader(os.Stdin)
fmt.Println("Configuration file not found.")
fmt.Print("Do you want to use default values? (yes/no): ")
useDefaults, _ := reader.ReadString('\n')
if strings.TrimSpace(useDefaults) != "yes" {
fmt.Print("Enter port (default 5000): ")
portStr, _ := reader.ReadString('\n')
if portStr != "\n" {
port, err := strconv.Atoi(strings.TrimSpace(portStr))
if err != nil {
config.Port = 5000
} else {
config.Port = port
}
}
fmt.Print("Enter your domain address (default localhost): ")
domain, _ := reader.ReadString('\n')
if domain != "\n" {
config.Domain = strings.TrimSpace(domain)
}
} else {
config = defaultConfig
}
if config.AuthCode == "" {
config.AuthCode = generateStrongRandomString(64)
fmt.Printf("Generated connection code: %s\n", config.AuthCode)
}
saveConfig(config)
return nil
}
func saveConfig(config Config) {
cfg := ini.Empty()
sec := cfg.Section("")
sec.Key("Port").SetValue(strconv.Itoa(config.Port))
sec.Key("AuthCode").SetValue(config.AuthCode)
sec.Key("PeerID").SetValue(config.PeerID)
peers := strings.Join(config.Peers, ",")
sec.Key("Peers").SetValue(peers)
sec.Key("Domain").SetValue(config.Domain)
err := cfg.SaveTo(configFilePath)
if err != nil {
fmt.Println("Error writing to config file:", err)
}
}
func loadConfig() Config {
cfg, err := ini.Load(configFilePath)
if err != nil {
log.Fatalf("Error opening config file: %v", err)
}
port, err := cfg.Section("").Key("Port").Int()
if err != nil || port == 0 {
port = 5000 // Default to 5000 if not set or error
}
peersStr := cfg.Section("").Key("Peers").String()
var peers []string
if peersStr != "" {
peers = strings.Split(peersStr, ",")
}
domain := cfg.Section("").Key("Domain").String()
if domain == "" {
domain = "localhost" // Default to localhost if not set
}
config = Config{
Port: port,
AuthCode: cfg.Section("").Key("AuthCode").String(),
PeerID: cfg.Section("").Key("PeerID").String(),
Peers: peers,
Domain: domain,
}
return config
}
func generateStrongRandomString(length int) string {
bytes := make([]byte, length)
_, err := rand.Read(bytes)
if err != nil {
log.Fatalf("Error generating random string: %v", err)
}
return base64.URLEncoding.EncodeToString(bytes)[:length]
}
func startFileWatcher() {
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
go func() {
defer watcher.Close()
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
if event.Op&fsnotify.Write == fsnotify.Write {
log.Println("Modified file:", event.Name)
configLock.Lock()
config = loadConfig()
configLock.Unlock()
// Perform your logic here to handle the changes in the config file
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
log.Println("Error:", err)
}
}
}()
err = watcher.Add(configFilePath)
if err != nil {
log.Fatal(err)
}
}