package main

import (
	"encoding/hex"
	"fmt"
	"github.com/songgao/packets/ethernet"
	"github.com/songgao/water"
	"log"
	"net"
	"net/http"
	"os"
	"os/exec"
	"strings"
)

var (
	self = net.ParseIP(os.Args[2])
	mask = net.IPv4Mask(255, 255, 255, 0)
)
var ifce, _ = water.New(water.Config{
	DeviceType: water.TAP,
})

func main() {
	//create http server
	http.HandleFunc("/rcv", rcv)
	go func() {
		http.ListenAndServe(":8181", nil)
	}()

	var frame ethernet.Frame
	setupIfce(net.IPNet{IP: self, Mask: mask}, ifce.Name())

	for {
		frame.Resize(1500)
		n, err := ifce.Read([]byte(frame))
		if err != nil {
			log.Fatal(err)
		}
		frame = frame[:n]
		log.Println("TRSV>>", frame)
		/*
			log.Printf("Dst: %s\n", frame.Destination())
			log.Printf("Src: %s\n", frame.Source())
			log.Printf("Ethertype: % x\n", frame.Ethertype())
			log.Printf("Payload: % x\n", frame.Payload())
		*/
		a := hex.EncodeToString(frame)
		resp, err := http.Get("http://" + os.Args[1] + "/rcv?packet=" + a)
		if err != nil {
			fmt.Println(err)
		} else {
			defer resp.Body.Close()
		}

	}
}

func rcv(w http.ResponseWriter, req *http.Request) {
	fmt.Fprintf(w, "OK\n")
	x, ok := req.URL.Query()["packet"]
	if !ok || len(x[0]) < 1 {
		fmt.Println("Url Param 'packet' is missing")
		return
	} else {
		log.Println("Reciving data!!!")
	}
	data, err := hex.DecodeString(x[0])
	if err != nil {
		log.Println(err)
	}
	log.Println("RECV<<", data)
	ifce.Write(data)
	if err != nil {
		log.Fatal(err)
	}
}

func setupIfce(ipNet net.IPNet, dev string) {
	sargs := fmt.Sprintf("interface ip set address name=REPLACE_ME source=static addr=REPLACE_ME mask=REPLACE_ME gateway=none")
	args := strings.Split(sargs, " ")
	args[4] = fmt.Sprintf("name=%s", dev)
	args[6] = fmt.Sprintf("addr=%s", ipNet.IP)
	args[7] = fmt.Sprintf("mask=%d.%d.%d.%d", ipNet.Mask[0], ipNet.Mask[1], ipNet.Mask[2], ipNet.Mask[3])
	cmd := exec.Command("netsh", args...)
	if err := cmd.Run(); err != nil {
		log.Println(err)
	}
}
