-- Autogenerated with DRAKON Editor 1.33
local table = table
local insert = table.insert
local string = string
local pairs = pairs
local ipairs = ipairs
local type = type

local tostring = tostring
local tonumber = tonumber
local tonumber64 = tonumber64
local print = print

local global_cfg = global_cfg

local clock = require("clock")
local log = require("log")
local digest = require("digest")
local fiber = require("fiber")
local io = require("io")
local os = require("os")
local utf8 = require("lua-utf8")

local utils = require("utils")
local ej = require("ej")
local external_creds = require("external_creds")

local g_from = global_cfg.email_from


setfenv(1, {}) 

function build_cmd(to, subject, headers, body_file)
    local esc_header
    local result = "mail -s \"" .. subject .. "\""
    for _, header in ipairs(headers) do
        result = result .. ' -a "' .. escape(header) .. '"'
    end
    result = result .. " \"" .. escape(to)
     .. "\" < " .. body_file
    return result
end

function dbg_email(to, attach)
    local text = "Hello Dimario,\n\n"
     .. "Thank you for registering at DrakonHub.\n"
     .. "Good luck creating good looking and accurate diagrams!\n\n"
     .. "Regards,\n"
     .. "DRAKON Editor team\n"
     .. "Чтобы получать сообщения на русском, выберите язык, находясь на сайте."
    local html = "<p>Hello Dimario,</p><br />\n"
     .. "<p>Thank you for registering at <strong>DrakonHub</strong>.</p>\n"
     .. "<p>Good luck creating good looking and accurate diagrams!</p><br />\n"
     .. "<p>Regards,</p>\n"
     .. "<p>DRAKON Editor team</p>\n"
     .. "<p style=\"font-size:80%\">Чтобы получать сообщения на русском, выберите язык, находясь на сайте.</p>"
    local subject = "Welcome to DrakonHub"
    send_mail(
    	to,
    	subject,
    	text,
    	html,
    	attach
    )
end

function encode_subject(original)
    local base64 = digest.base64_encode(original)
    base64 = base64:gsub("\n", "")
    return "=?UTF-8?B?" .. base64 .. "?="
end

function escape(str)
    return utils.replace(str, "\"", "\\\"")
end

function get_template(language, filename)
    local path = global_cfg.emails_dir
     .. "/" .. language .. "-" .. filename
    local data = utils.read_all_bytes(path)
    if data then
        return data
    else
        error(
        	"Could not load email template from "
        	.. path
        )
    end
end

function log_email(user_id, to, subject, text, attach)
    local data = {
    	user_id = user_id,
    	subject = subject,
    	to = to
    }
    ej.info("email", data)
end

function make_body(text, html, separator, attach)
    local text_sep = "_part_"
     .. utils.random_string()
    local lines = {}
    insert(lines, "")
    insert(lines, "This is a multi-part message in MIME format.")
    insert(lines, "")
    insert(lines, "--" .. separator)
    insert(lines, "Content-Type: multipart/alternative; boundary=\""
     ..text_sep .. "\"")
    insert(lines, "")
    insert(lines, "--" .. text_sep)
    insert(lines, "Content-Type: text/plain; charset=UTF-8; format=flowed")
    insert(lines, "Content-Transfer-Encoding: base64")
    insert(lines, "")
    insert(lines, digest.base64_encode(text))
    insert(lines, "")
    if html then
        insert(lines, "--" .. text_sep)
        insert(lines, "Content-Type: text/html; charset=UTF-8")
        insert(lines, "Content-Transfer-Encoding: base64")
        insert(lines, "")
        insert(lines, digest.base64_encode(html))
        insert(lines, "")
    end
    insert(lines, "--" .. text_sep .. "--")
    insert(lines, "")
    if attach then
        local attach_body = utils.load_as_base64(
        	attach
        )
        local mime = utils.get_mime(
        	attach,
        	"text/plain; charset=UTF-8"
        )
        local filename = utils.get_filename(attach)
        insert(lines, "--" .. separator)
        insert(lines, "Content-Type: " .. mime)
        insert(lines, "Content-Transfer-Encoding: base64")
        insert(lines, "Content-Disposition: attachment; "
         .. "filename=\"" .. filename .. "\"")
        insert(lines, "")
        insert(lines, attach_body)
        insert(lines, "")
    end
    insert(lines, "--" .. separator .. "--")
    insert(lines, "")
    return utils.join(lines, "\n")
end

function make_headers(from, separator)
    local headers = {}
    table.insert(
    	headers,
    	"From: " .. from
    )
    table.insert(
    	headers,
    	"MIME-Version: 1.0"
    )
    table.insert(
    	headers,
    	'Content-Type: multipart/mixed;boundary="'
    	.. separator .. '"'
    )
    return headers
end

function make_separator()
    return "_separator_" .. utils.random_string()
end

function make_tmp_filename()
    local filename = global_cfg.tmp .. "/"
     .. utils.random_string()
    return filename
end

function send_mail(user_id, to, subject, text, html, attach)
    if global_cfg.mg then
        send_mg(
        	user_id,
        	to,
        	subject,
        	text,
        	html,
        	attach
        )
    else
        send_sendmail(
        	user_id,
        	to,
        	subject,
        	text,
        	html,
        	attach
        )
    end
    log_email(
    	user_id,
    	to,
    	subject,
    	text,
    	attach
    )
end

function send_mg(user_id, to, subject, text, html, attach)
    local key = external_creds.mg_key
    local sender = g_from
    local mg = "https://api.mailgun.net/v3/mg."
    mg = "https://api.eu.mailgun.net/v3/mg."
    local subject2 = utils.bash_escape(subject)
    local text2 = utils.bash_escape(text)
    local command = "curl -s --user 'api:" .. key .. "' " ..
      mg  .. global_cfg.my_domain .. "/messages " ..
      "-F from='" .. sender .. "' " ..
      "-F to='" .. to .. "' " ..
      "-F subject='" .. subject2 .. "' " ..
      "-F text='" .. text2 .. "' "
    if html then
        local html2 = utils.bash_escape(html)
        command = command ..  
         "--form-string html='<html>" .. html2 .. "</html>' "
    end
    if attach then
        command = command ..  
         "-F attachment='@" .. attach .. "' "
    end
    os.execute(command)
end

function send_real_email(to, subject, headers, body)
    local body_filename = make_tmp_filename()
    utils.write_all_bytes(
    	body_filename,
    	body
    )
    local subj2 = encode_subject(subject)
    local command = build_cmd(
    	to,
    	subj2,
    	headers,
    	body_filename
    )
    local code = os.execute(command)
    os.remove(body_filename)
    return code
end

function send_sendmail(user_id, to, subject, text, html, attach)
    local separator = make_separator()
    local body = make_body(
    	text,
    	html,
    	separator,
    	attach
    )
    local headers = make_headers(
    	g_from,
    	separator
    )
    if global_cfg.debug_mail then
        write_debug_email(
        	to,
        	subject,
        	headers,
        	body
        )
    else
        send_real_email(
        	to,
        	subject,
        	headers,
        	body
        )
    end
end

function write_debug_email(to, subject, headers, body)
    local body_filename = make_tmp_filename()
    local d = clock.time()
    local date = os.date("%Y%m%d-%H%M%S", d)
    local filename = global_cfg.tmp .. "/"
     .. date .. ".txt"
    local file = io.open(filename, "wb")
    file:write(to, "\n")
    file:write(subject, "\n")
    local subj2 = encode_subject(subject)
    local command = build_cmd(
    	to,
    	subj2,
    	headers,
    	body_filename
    )
    file:write(command, "\n")
    utils.write_all_bytes(
    	body_filename,
    	body
    )
    for _, header in ipairs(headers) do
        file:write(header, "\n")
    end
    file:write(body, "\n")
    file:close()
end


return {
	dbg_email = dbg_email,
	send_mail = send_mail,
	get_template = get_template
}
