package main

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

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

var RCV_B = 0
var TXT_B = 0

func main() {
	//for stat only
	go func() {
		for {
			log.Println("Total reciving: ", RCV_B, ", Total transmitting: ", TXT_B)
			time.Sleep(5 * time.Second)
		}
	}()

	//create http server
	go func() {
		fmt.Println("Launching server...")
		// listen on all interfaces
		ln, _ := net.Listen("tcp", ":8081")
		// accept connection on port
		conn, _ := ln.Accept()
		// run loop forever (or until ctrl-c)
		for {
			// will listen for message to process ending in newline (\n)
			message, _ := bufio.NewReader(conn).ReadString('\n')
			// output message received
			//fmt.Print("RECV<<",  string(message))
			RCV_B += len(string(message))
			data, err := hex.DecodeString(strings.ReplaceAll("\n", "", string(message)))
			if err != nil {
				//log.Println(err)
			}
			//log.Println("RECV<<", data)
			ifce.Write(data)
		}
	}()

	//declare server
	// connect to server
	conns, _ := net.Dial("tcp", os.Args[1]+":8081")

	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>>", hex.EncodeToString(frame))
		TXT_B += len(hex.EncodeToString(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())
			log.Printf("HEX: % x\n", frame)
		*/
		fmt.Fprintf(conns, hex.EncodeToString(frame)+"\n")
		/*
			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 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)
	}
}
