// Copyright 2021 iLogtail Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package util

import (
	"errors"
	"log"
	"net"
	"os"
)

var ipAddress string
var hostName string

func init() {
	var err error
	ipAddress, err = getExternalIP()
	if err != nil {
		log.Println(err)
	}
	hostName, _ = os.Hostname()
}

// SetNetworkIdentification updates return values of GetIPAddress and GetHostName.
// NOTE: It is not thread-safety, this is called by plugin_manager.LoadGlobalConfig only.
func SetNetworkIdentification(hostIP, hostname string) {
	ipAddress = hostIP
	hostName = hostname
}

func GetIPAddress() string {
	return ipAddress
}

func GetHostName() string {
	return hostName
}

func getExternalIP() (string, error) {
	ifaces, err := net.Interfaces()
	if err != nil {
		return "", err
	}
	for _, iface := range ifaces {
		if iface.Flags&net.FlagUp == 0 {
			continue // interface down
		}
		if iface.Flags&net.FlagLoopback != 0 {
			continue // loopback interface
		}
		addrs, err := iface.Addrs()
		if err != nil {
			return "", err
		}
		for _, addr := range addrs {
			var ip net.IP
			switch v := addr.(type) {
			case *net.IPNet:
				ip = v.IP
			case *net.IPAddr:
				ip = v.IP
			}
			if ip == nil || ip.IsLoopback() {
				continue
			}
			ip = ip.To4()
			if ip == nil {
				continue // not an ipv4 address
			}
			return ip.String(), nil
		}
	}
	return "", errors.New("are you connected to the network?")
}

func TryConvertLocalhost2RealIP(ip string) string {
	if ip == "localhost" || ip == "127.0.0.1" || ip == "0.0.0.0" {
		return GetIPAddress()
	}
	return ip
}
