-- Autogenerated with DRAKON Editor 1.32
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 = "Drakon.Tech Support <support@mg.drakonhub.com>"


setfenv(1, {}) 

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

function dbg_email(to, attach)
    -- item 60
    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"
     .. "Чтобы получать сообщения на русском, выберите язык, находясь на сайте."
    -- item 61
    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>"
    -- item 62
    local subject = "Welcome to DrakonHub"
    -- item 63
    send_mail(
    	to,
    	subject,
    	text,
    	html,
    	attach
    )
end

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

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

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

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

function make_body(text, html, separator, attach)
    -- item 128
    local text_sep = "_part_"
     .. utils.random_string()
    -- item 41
    local lines = {}
    -- item 42
    insert(lines, "")
    insert(lines, "This is a multi-part message in MIME format.")
    insert(lines, "")
    -- item 129
    insert(lines, "--" .. separator)
    insert(lines, "Content-Type: multipart/alternative; boundary=\""
     ..text_sep .. "\"")
    insert(lines, "")
    -- item 39
    insert(lines, "--" .. text_sep)
    insert(lines, "Content-Type: text/plain; charset=UTF-8; format=flowed")
    insert(lines, "Content-Transfer-Encoding: base64")
    insert(lines, "")
    -- item 43
    insert(lines, digest.base64_encode(text))
    insert(lines, "")
    -- item 131
    if html then
        -- item 44
        insert(lines, "--" .. text_sep)
        insert(lines, "Content-Type: text/html; charset=UTF-8")
        insert(lines, "Content-Transfer-Encoding: base64")
        insert(lines, "")
        -- item 45
        insert(lines, digest.base64_encode(html))
        insert(lines, "")
    end
    -- item 130
    insert(lines, "--" .. text_sep .. "--")
    insert(lines, "")
    -- item 122
    if attach then
        -- item 127
        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)
        -- item 125
        insert(lines, "--" .. separator)
        insert(lines, "Content-Type: " .. mime)
        insert(lines, "Content-Transfer-Encoding: base64")
        insert(lines, "Content-Disposition: attachment; "
         .. "filename=\"" .. filename .. "\"")
        -- item 126
        insert(lines, "")
        insert(lines, attach_body)
        insert(lines, "")
    end
    -- item 40
    insert(lines, "--" .. separator .. "--")
    insert(lines, "")
    -- item 46
    return utils.join(lines, "\n")
end

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

function make_separator()
    -- item 27
    return "_separator_" .. utils.random_string()
end

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

function send_mail(user_id, to, subject, text, html, attach)
    -- item 212
    if global_cfg.mg then
        -- item 215
        send_mg(
        	user_id,
        	to,
        	subject,
        	text,
        	html,
        	attach
        )
    else
        -- item 182
        send_sendmail(
        	user_id,
        	to,
        	subject,
        	text,
        	html,
        	attach
        )
    end
    -- item 216
    log_email(
    	user_id,
    	to,
    	subject,
    	text,
    	attach
    )
end

function send_mg(user_id, to, subject, text, html, attach)
    -- item 221
    local key = external_creds.mg_key
    local sender = g_from
    local mg = "https://api.mailgun.net/v3/mg.drakonhub.com"
    -- item 228
    local subject2 = utils.bash_escape(subject)
    local text2 = utils.bash_escape(text)
    -- item 224
    local command = "curl -s --user 'api:" .. key .. "' " ..
      mg  .. "/messages " ..
      "-F from='" .. sender .. "' " ..
      "-F to='" .. to .. "' " ..
      "-F subject='" .. subject2 .. "' " ..
      "-F text='" .. text2 .. "' "
    -- item 229
    if html then
        -- item 232
        local html2 = utils.bash_escape(html)
        -- item 233
        command = command ..  
         "--form-string html='<html>" .. html2 .. "</html>' "
    end
    -- item 234
    if attach then
        -- item 237
        command = command ..  
         "-F attachment='@" .. attach .. "' "
    end
    -- item 226
    os.execute(command)
end

function send_real_email(to, subject, headers, body)
    -- item 113
    local body_filename = make_tmp_filename()
    -- item 116
    utils.write_all_bytes(
    	body_filename,
    	body
    )
    -- item 162
    local subj2 = encode_subject(subject)
    -- item 114
    local command = build_cmd(
    	to,
    	subj2,
    	headers,
    	body_filename
    )
    -- item 115
    local code = os.execute(command)
    -- item 117
    os.remove(body_filename)
    -- item 118
    return code
end

function send_sendmail(user_id, to, subject, text, html, attach)
    -- item 194
    local separator = make_separator()
    -- item 191
    local body = make_body(
    	text,
    	html,
    	separator,
    	attach
    )
    -- item 193
    local headers = make_headers(
    	g_from,
    	separator
    )
    -- item 217
    if global_cfg.debug_mail then
        -- item 219
        write_debug_email(
        	to,
        	subject,
        	headers,
        	body
        )
    else
        -- item 195
        send_real_email(
        	to,
        	subject,
        	headers,
        	body
        )
    end
end

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


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