//go:build linux

package route_test

import (
	"fmt"
	"net"
	"net/netip"
	"testing"
	"time"

	"github.com/alexfalkowski/go-linux/v2/internal/test"
	"github.com/alexfalkowski/go-linux/v2/netlink"
	"github.com/alexfalkowski/go-linux/v2/netlink/route"
	"github.com/stretchr/testify/require"
)

func ExampleConn_Links() {
	conn, err := route.Open(netlink.Options{Validation: netlink.StrictValidation})
	if err != nil {
		panic(err)
	}
	defer conn.Close()

	if err := conn.SetDeadline(time.Now().Add(5 * time.Second)); err != nil {
		panic(err)
	}
	links, err := conn.Links()
	if err != nil {
		panic(err)
	}
	for _, link := range links {
		if link.Flags&route.Loopback != 0 {
			fmt.Println(link.Name)
		}
	}

	// Output: lo
}

func ExampleConn_Routes() {
	conn, err := route.Open(netlink.Options{})
	if err != nil {
		panic(err)
	}
	defer conn.Close()

	if err := conn.SetDeadline(time.Now().Add(5 * time.Second)); err != nil {
		panic(err)
	}
	routes, err := conn.Routes(route.IPv4)
	if err != nil {
		panic(err)
	}
	for _, entry := range routes {
		if !entry.Destination.Addr().Is4() {
			panic("unexpected address family")
		}
	}
	fmt.Println("IPv4 route dump complete")

	// Output: IPv4 route dump complete
}

// The link dump contains the endpoint created in the private network namespace.
//
//	host0
func ExampleConn_AddVeth() {
	// Run in a private network namespace with CAP_NET_ADMIN.
	conn, err := route.Open(netlink.Options{})
	if err != nil {
		panic(err)
	}
	defer conn.Close()
	if err := conn.SetDeadline(time.Now().Add(5 * time.Second)); err != nil {
		panic(err)
	}

	if err := conn.AddVeth(route.VethConfig{Name: "host0", PeerName: "peer0"}); err != nil {
		panic(err)
	}
	links, err := conn.Links()
	if err != nil {
		panic(err)
	}
	for _, link := range links {
		if link.Name == "host0" {
			fmt.Println(link.Name)
			if err := conn.DeleteLink(link.Index); err != nil {
				panic(err)
			}
			return // Deleting one endpoint removes both.
		}
	}
	panic("host0 is missing")
}

func TestAddVethExample(t *testing.T) {
	if !test.NetworkNamespace(t) {
		return
	}
	require.Equal(t, "host0\n", test.ExampleOutput(t, ExampleConn_AddVeth))
}

// The kernel acknowledges the permanent neighbor on the dummy link.
//
//	added 192.0.2.2 on demo0
func ExampleConn_AddNeighbor() {
	// Run in a private network namespace with CAP_NET_ADMIN.
	conn, err := route.Open(netlink.Options{})
	if err != nil {
		panic(err)
	}
	defer conn.Close()

	if err := conn.SetDeadline(time.Now().Add(5 * time.Second)); err != nil {
		panic(err)
	}
	if err := conn.AddLink("demo0", route.Dummy); err != nil {
		panic(err)
	}
	// Resolve the interface index in the same namespace as conn.
	link, err := net.InterfaceByName("demo0")
	if err != nil {
		panic(err)
	}
	address := netip.MustParseAddr("192.0.2.2")
	if err := conn.AddNeighbor(route.NeighborConfig{
		Index: link.Index, Address: address, State: route.NeighborPermanent,
		HardwareAddr: net.HardwareAddr{2, 0, 0, 0, 0, 2},
	}); err != nil {
		panic(err)
	}
	fmt.Printf("added %s on %s\n", address, link.Name)
	if err := conn.DeleteNeighbor(link.Index, address); err != nil {
		panic(err)
	}
	if err := conn.DeleteLink(link.Index); err != nil {
		panic(err)
	}
}

func TestAddNeighborExample(t *testing.T) {
	if !test.NetworkNamespace(t) {
		return
	}
	require.Equal(t, "added 192.0.2.2 on demo0\n", test.ExampleOutput(t, ExampleConn_AddNeighbor))
}

// The kernel acknowledges the source rule and its routing table.
//
//	added rule for 192.0.2.0/24 using table 1001
func ExampleConn_AddRule() {
	// Run in a private network namespace with CAP_NET_ADMIN.
	conn, err := route.Open(netlink.Options{})
	if err != nil {
		panic(err)
	}
	defer conn.Close()

	if err := conn.SetDeadline(time.Now().Add(5 * time.Second)); err != nil {
		panic(err)
	}
	ruleConfig := route.RuleConfig{
		Family: route.IPv4, Priority: 100, Action: route.RuleLookup, Table: 1001,
		Selector: route.RuleSelector{Source: netip.MustParsePrefix("192.0.2.0/24")},
	}
	if err := conn.AddRule(ruleConfig); err != nil {
		panic(err)
	}
	fmt.Printf("added rule for %s using table %d\n", ruleConfig.Selector.Source, ruleConfig.Table)
	if err := conn.DeleteRule(ruleConfig); err != nil {
		panic(err)
	}
}

func TestAddRuleExample(t *testing.T) {
	if !test.NetworkNamespace(t) {
		return
	}
	require.Equal(t, "added rule for 192.0.2.0/24 using table 1001\n", test.ExampleOutput(t, ExampleConn_AddRule))
}

func ExampleConn_LookupRoute() {
	conn, err := route.Open(netlink.Options{Validation: netlink.StrictValidation})
	if err != nil {
		panic(err)
	}
	defer conn.Close()

	if err := conn.SetDeadline(time.Now().Add(5 * time.Second)); err != nil {
		panic(err)
	}
	path, err := conn.LookupRoute(route.RouteQuery{Destination: netip.MustParseAddr("127.0.0.1")})
	if err != nil {
		panic(err)
	}
	fmt.Println(path.Destination, path.Type == route.Local)

	// Output: 127.0.0.1 true
}

// The kernel acknowledges the route through the named nexthop.
//
//	added 192.0.2.0/24 via nexthop 42
func ExampleConn_AddRouteWithPaths() {
	// Run with CAP_NET_ADMIN in a private network namespace with an active uplink0.
	conn, err := route.Open(netlink.Options{})
	if err != nil {
		panic(err)
	}
	defer conn.Close()

	if err := conn.SetDeadline(time.Now().Add(5 * time.Second)); err != nil {
		panic(err)
	}
	link, err := net.InterfaceByName("uplink0")
	if err != nil {
		panic(err)
	}

	nextHop := route.NexthopConfig{ID: 42, Family: route.IPv4, Index: link.Index}
	if err := conn.AddNexthop(nextHop); err != nil {
		panic(err)
	}

	config := route.RouteConfig{Destination: netip.MustParsePrefix("192.0.2.0/24")}
	paths := route.RoutePathConfig{NexthopID: nextHop.ID}
	if err := conn.AddRouteWithPaths(config, paths); err != nil {
		panic(err)
	}
	fmt.Printf("added %s via nexthop %d\n", config.Destination, paths.NexthopID)
	if err := conn.DeleteRouteWithPaths(config, paths); err != nil {
		panic(err)
	}
	if err := conn.DeleteNexthop(nextHop.ID); err != nil {
		panic(err)
	}
}

func TestAddRouteWithPathsExample(t *testing.T) {
	if !test.NetworkNamespace(t) {
		return
	}
	test.RouteDummy(t, test.Route(t), "uplink0")
	require.Equal(t, "added 192.0.2.0/24 via nexthop 42\n", test.ExampleOutput(t, ExampleConn_AddRouteWithPaths))
}
