package util

import (
	"crypto/rand"
	"github.com/google/gopacket"
	"github.com/google/gopacket/layers"
	"github.com/google/gopacket/pcapgo"
	log "github.com/sirupsen/logrus"
	"io/ioutil"
	"net"
	"os"
	"strconv"
)

// WritePcap writes the provided data to a given pcap file
func WritePcap(file string, data []byte, ci gopacket.CaptureInfo) {
	f, err := os.Create(file)
	if err != nil {
		log.Errorf("Error writing pcap file %s", file)
	}
	defer f.Close()

	r, err := pcapgo.NewNgWriter(f, layers.LinkTypeEthernet)
	if err != nil {
		log.Errorf("Error writing pcap file %s", file)
	}
	defer r.Flush()

	err = r.WritePacket(ci, data)
}

// WriteBinary writes the provided data to a given binary file
func WriteBinary(file string, data []byte) {
	if err := ioutil.WriteFile(file, data, 0644); err != nil {
		log.Errorf("Error writing binary file %s", file)
	}
}

func WritePIDFile(filename string) {
	if filename == "" {
		return
	}
	if err := ioutil.WriteFile(filename, []byte(strconv.Itoa(os.Getpid()) + "\n"), 0644); err != nil {
		log.Errorf("Error writing PID file %s", filename)
	}
}

func GenerateMac(customMAC string) net.HardwareAddr {
	if customMAC != "" {
		ret, _ := net.ParseMAC("52:54:00:12:34:aa")
		return ret
	}
	buf := make([]byte, 6)
	var mac net.HardwareAddr
	if _, err := rand.Read(buf); err != nil {
		log.Error("Error generating random mac")
		ret, _ := net.ParseMAC("52:54:00:12:34:aa")
		return ret
	}
	// Set local bit, ensure unicast address
	buf[0] = (buf[0] | 2) & 0xfe
	mac = append(mac, buf[0], buf[1], buf[2], buf[3], buf[4], buf[5])
	return mac
}
