package smtp

import (
	"git.loafle.net/overflow/overflow_probe/discovery/core/scan/service/matcher/packet"
	"git.loafle.net/overflow/overflow_probe/discovery/discovery/types"
	"strings"
)

type SmtpMatcher struct {
	packets []*packet.Packet
}

func NewSmtpMatcher() *SmtpMatcher {

	m := &SmtpMatcher{}
	b := []byte("helo test\r\n")
	m.packets = append(m.packets, packet.NewPacket(b, len(b)))
	b = []byte("quit\r\n")
	m.packets = append(m.packets, packet.NewPacket(b, len(b)))
	return m
}

func (t *SmtpMatcher) ServiceName() string {
	return "SMTP"
}

func (t *SmtpMatcher) PacketCount() int {
	return len(t.packets)
}
func (t *SmtpMatcher) Packet(index int) *packet.Packet {
	return t.packets[index]
}

func (t *SmtpMatcher) IsError(index int, packet *packet.Packet, info *types.ServiceScanInfo) bool {
	return false
}

func (t *SmtpMatcher) IsNoResponse(index int) bool {
	return false
}

func (t *SmtpMatcher) IsPrePacket() bool {
	return true
}

func (t *SmtpMatcher) Match(index int, packet *packet.Packet, info *types.ServiceScanInfo) bool {
	if packet == nil {
		return false
	}
	buf := string(packet.Buffer)
	if len(buf) == 0 || len(buf) < 5 {
		return false
	}

	splits := strings.Split(buf, "\r\n")
	splits = strings.Split(buf, " ")
	if index == 0 {
		if splits[0] == "220" {
			return true
		}
	} else if index == 1 {
		if splits[0] == "250" {
			return true
		}
	} else if index == 2 {
		if splits[0] == "221" {
			return true
		}
	}
	return false
}
