package main

import (
	"encoding/hex"
	"fmt"
	"github.com/inszva/tap0901"
	"net"
	"net/http"
	//"net/url"
	"log"
	"os"
	"sync"
	"time"
)

//Create a new virtual network interface
var tun, _ = tap0901.OpenTun(net.ParseIP(os.Args[2]), net.ParseIP(os.Args[4]), net.ParseIP(os.Args[3]))

func main() {
	//tun, err := tap0901.OpenTun(net.IP([]byte{0, 0, 0, 0}), net.IP([]byte{0, 0, 0, 0}), net.IP([]byte{0, 0, 0, 0}))
	/*
		if err != nil {
			panic(err)
		}
	*/
	fmt.Println("Virtual Network Interface Created")
	time.Sleep(2 * time.Second)

	// type IP

	IPAddress := net.ParseIP(os.Args[2])
	SubNet := net.ParseIP(os.Args[3])
	GateW := net.ParseIP(os.Args[4])

	//create fucking DHCP IP
	err := tun.SetDHCPMasq(IPAddress, SubNet, GateW, net.IP([]byte{0, 0, 0, 0}))
	if err != nil {
		fmt.Println(err)
	}

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

	tun.Connect()
	time.Sleep(2 * time.Second)
	szName := tun.GetNetworkName(false)
	fmt.Println("Interface name: ", szName)
	fmt.Println("Dest IP:" + os.Args[1])

	tun.SetReadHandler(func(tun *tap0901.Tun, data []byte) {
		a := hex.EncodeToString(data)
		//bs, _ := hex.DecodeString(a)
		//fmt.Println(string(bs))
		log.Println("TXT>>", dde(data))
		//tun.Write(dde(data))

		resp, err := http.Get("http://" + os.Args[1] + "/rcv?packet=" + a)
		if err != nil {
			fmt.Println(err)
		} else {
			defer resp.Body.Close()
		}

	})
	wp := sync.WaitGroup{}
	wp.Add(1)
	go func() {
		tun.Listen(1)
		wp.Done()
	}()

	fmt.Println(tun.GetMTU(false))
	//fmt.Println()
	/*
		for {
			time.Sleep(3 * time.Second)
			tun.Write([]byte("Hello World"))
			fmt.Println("Waiting")
		}
		time.Sleep(10 * time.Second)
		tun.SignalStop()
	*/
	wp.Wait()
}

func rcv(w http.ResponseWriter, req *http.Request) {
	fmt.Fprintf(w, "hello\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<<", dde(data))
	tun.Write(dde(data))
}

func dde(packet []byte) []byte {
	var i = len(packet) - 1
	for packet[i] == 0 {
		//--i
		i--
	}

	//var temp = [i + 1]byte
	temp := make([]byte, i+1)
	//Array.Copy(packet, temp, i + 1)
	temp = packet[0 : i+1]
	return temp
}
