package netmgr

import (
	"context"
	"net"
	"net/http"
	"os/exec"
	"strings"
	"time"
)

const (
	///////////////////////////////////////
	// 白名单联网检测地址
	TEST_URL1 = "www.aliyun.com"
	TEST_URL2 = "http://www.aliyun.com"
	TEST_HOST = "223.5.5.5" // 阿里云DNS主机
	///////////////////////////////////////
	TEST_TIMEOUT = 5 * time.Second
)

func test1() bool {
	_, err := net.LookupHost(TEST_URL1)
	return err == nil
}

func test2() bool {
	ctx, cancel := context.WithTimeout(context.Background(), TEST_TIMEOUT)
	defer cancel()

	cmd := exec.CommandContext(ctx, "ping", "-c", "3", TEST_HOST)

	out, err := cmd.CombinedOutput()
	if err != nil {
		return false
	}

	return strings.Contains(strings.ToLower(string(out)), "ttl=")
}

func test3() bool {
	conn, err := net.DialTimeout("tcp", TEST_HOST+":53", TEST_TIMEOUT)
	if err != nil {
		return false
	}
	conn.Close()
	return true
}

func test4() bool {
	client := http.Client{
		Timeout: TEST_TIMEOUT,
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			return http.ErrUseLastResponse
		},
	}
	resp, err := client.Head(TEST_URL2)
	if err != nil {
		return false
	}
	resp.Body.Close()
	return true
}

func CheckNetwork() (dnsOK, pingOK, tcpOK, httpOK bool) {
	bOK1 := test1()
	bOK3 := test3()
	bOK4 := test4()
	bOK2 := test2() || bOK3 || bOK4
	return bOK1, bOK2, bOK3, bOK4
}
