package main

import (
	"fmt"
	"os/exec"
	"strings"
)

func setNetworkConfig(info *DeviceInfo) error {
	fmt.Printf("Setting IP: %s\n", info.DLCIP)
	return setIPAddress("eth0", info.DLCIP, "24")
}

func setIPAddress(interfaceName, ipAddress, netmask string) error {
	fmt.Printf("Setting IP address: %s\n", ipAddress)

	cmd := exec.Command("ip", "addr", "add", ipAddress+"/"+netmask, "dev", interfaceName)
	output, err := cmd.CombinedOutput()
	if err != nil {
		result := string(output)
		if strings.Contains(result, "File exists") {
			return nil
		}
		return fmt.Errorf("failed to set IP address: %v, output: %s", err, output)
	}
	return setIfconfigUp()
}

func setIfconfigUp() error {
	cmd := exec.Command("ip", "link", "set", "eth0", "up")
	output, err := cmd.CombinedOutput()
	if err != nil {
		return fmt.Errorf("failed to set interface up: eth0, err: %v, output: %s", err, output)
	}
	return nil
}
