# signature { license=0, seed=277031123, key="3e1c2d609738e5014e6d91b8062d73eb" }
-- ----------------------------------------------------------------------------



local socket = require( 'socket' )
local gsub = string.gsub

local cfg = _G.cfg





local i18nTexts = cfg.read( 'i18n.txt' ).i18n
local function i18n( key, default) return i18nTexts[key] or default or key end






local puretcp = {} -- holds original TCP sockets

local function ssl_connect( self, address, port )
	local fd = self:getfd()
	local pure = puretcp[ fd ]
	if not pure then
		print("can't find pure socket with handle "..fd)
		return
	end

	pure:setfd( fd ) -- reinstall the OS socket handle
	local ret, err = pure:connect( address, port )
	if not ret then
		print("connecting pure socket yielded '"..err..'"')
		return
	end

	pure:setfd( -1 )
	puretcp[ fd ] = nil

	repeat
		local ok, msg = self:dohandshake()
	until _G.stopped or ok or  (msg ~= 'wantread' and msg ~= 'wantwrite')

	return 1 -- like tcp.connect
end

local ssl = require( 'ssl' )
ssl.tcp = function()
	local pure = socket.tcp()       -- create a TCP socket

	puretcp[ pure:getfd() ] = pure  -- register where ssl_connect can find it
	local wrapped = ssl.wrap( pure, {mode='client', protocol='tlsv1_2'} )



	local ssl_mt = getmetatable( wrapped ) -- this is what wrapped can do
	ssl_mt.__index.connect = ssl_connect;  -- now it knows how to connect()
	return wrapped
end







local function substitute( text, T )
	T.cfg = T.cfg or cfg -- add configuration
	text = gsub( text, '{(%w+)}', T )
	text = gsub( text, '{(%w+)%.(%w+)}', function( t,k ) return tostring( T[t][k]) end )

	return text
end




local function send( T )
	if not T.to then return end
	if (cfg.SmtpServer or '') < ' ' then
		log( i18n("No SMTP server configured") )
		return
	end

	local smtp = import( 'socket.smtp' )
	smtp.TIMEOUT = 10

	smtp.DOMAIN = (cfg.EmailFrom or ''):match( '@(.*)' ) or _G.OwnIP or 'noreply.com'


	local subject = substitute( T.subject or '', T ):gsub( '%c', '' )


	local body = substitute( T.body or '', T ):gsub( '\r?\n', '\r\n' )


	local rcpt = '<'..T.to..'>'
	local from = '<'..cfg.EmailFrom..'>'
	local mesgt =
	{
		headers =
		{
			to = rcpt,
			from = from,
			subject = subject,
			['content-type'] = 'text/plain; charset=utf-8',
			['content-transfer-encoding'] = '8bit',
		},
		body = body,
	}

	local password = cfg:password( 'Smtp' )

	if password == '' then password = nil end

	log( i18n("sending email:"), subject, i18n("to"), T.to )
	local ok, whynot = smtp.send
	{
		from     = from,
		rcpt     = rcpt,

		user     = cfg.SmtpUsername,
		password = password,
		server   = cfg.SmtpServer,
		port     = cfg.SmtpPort,

		source   = smtp.message( mesgt ),

		create   = cfg.SmtpSecurity==1 and ssl.tcp or socket.tcp,
	}

	if not ok then
		log( i18n("Email problem:"), whynot )
	end

	return ok, whynot
end

local subject, body
local result = _G.Email



if result == 'License registered successfully.' then
	subject, body = i18n("SubjectSuccess"), i18n("EmailSuccess")
else
	subject, body = i18n("SubjectFailed"), i18n("EmailFailed")
end


local mail =
{
	send    = send,
	to      = cfg.DealerEmail,
	subject = subject,
	body    = body,
	Name    = cfg.DealerName,
	Reason  = result,
}


if not _G.DealerSentOk then
	if not mail:send() then return end
	_G.DealerSentOk = true
end


mail.to     = cfg.CustomerEmail
mail.Name   = cfg.CustomerName

if mail:send() then
	_G.Email = false
	_G.DealerSentOk = false
end
