package main

import (
	"fmt"
	"log"
	"net"
	"net/http"
	"os"
	"path"
	"strings"
)

func logout(w http.ResponseWriter, r *http.Request) {
	if addr := r.Header.Get("X-Forwarded-For"); addr != "" {
		r.RemoteAddr = addr
	}
	log.Printf("%s \"%s %s\" [%s]\n", r.RemoteAddr, r.Method, r.URL.Path, r.UserAgent())

	w.Header().Set("Content-Type", "text/plain")

	// Find corresponding MAC
	var fname string
	spl := strings.SplitN(r.RemoteAddr, ":", 2)
	if ip := net.ParseIP(spl[0]); ip == nil {
		http.Error(w, "Unable to parse given IPv4: "+spl[0], http.StatusInternalServerError)
		return
	} else if arptable, err := ARPAnalyze(); err != nil {
		http.Error(w, "Unable to logout: "+err.Error(), http.StatusInternalServerError)
		return
	} else if arpent := ARPContainsIP(arptable, ip); arpent == nil {
		http.Error(w, "Unable to find MAC in ARP table to logout.", http.StatusInternalServerError)
		return
	} else {
		fname = fmt.Sprintf("%02x-%02x-%02x-%02x-%02x-%02x-%02x", arpent.HWType, arpent.HWAddress[0], arpent.HWAddress[1], arpent.HWAddress[2], arpent.HWAddress[3], arpent.HWAddress[4], arpent.HWAddress[5])
	}

	if err := os.Remove(path.Join(tftpDir, "pxelinux.cfg", fname)); err != nil {
		log.Println("Error on logout action:", err)
		http.Error(w, "Unable to logout: "+err.Error(), http.StatusInternalServerError)
		return
	}

	log.Println("Successful logout from", r.RemoteAddr)
	http.Error(w, "Success", http.StatusOK)
}
