<%@language = "javascript" %>
<% /*
     $Revision$
     $Id$

    File:               fac_refresh_accept_save.asp
    Description:        Refresh de acceptatie database
    Parameters:

    Context:
    Note:               Er wordt alleen een batchfile aangemaakt.
                        Op de achtergrond moet wel een geplande taak zijn
                        die het ook echt uitvoert.
*/
%>
<%
var JSON_Result = true;
%>
<!-- #include file="../Shared/common.inc" -->
<%
protectRequest.validateToken();
user.checkAutorisation("WEB_FACRFR");

var emailadr_to = getFParam("emailadr", "");  // is het een geldig mailadres?
var batchfile = S("refreshfromdumpscriptfolder") + "\\refresh_" + customerId + "_TEST.bat"
var fac_refresh_anon = getFParamSafe("fac_refresh_anon", "");

var fso = Server.CreateObject("Scripting.FileSystemObject");
var ForReading = 1;
var ForWriting = 2;
var ForAppending = 8
var tsUnicode = -1;
var tsAscii = 0;

// Achterhaal het wachtwoord van de doelomgeving uit de udl
function read_ora_udl()
{
    var fullPath = Server.MapPath("../../CUST");
    var ora_udl = fullPath + "\\" + customerId + "\\oracle.udl";

    var f = fso.OpenTextFile(ora_udl, ForReading, true, tsUnicode);
    var s = f.ReadLine();
    s = f.ReadLine();
    s = f.ReadLine(); //3e regel is interessant
    // Provider=OraOLEDB.Oracle.1;Password=xxxxx;Persist Security Info=True;User ID=hcas_test;Data Source=fclt
    var sa = s.split(";");
    var data = {};
    for (var i = 0; i < sa.length; i++)
    {
        var itma = sa[i].split("=");
        if (itma.length == 2)
        {
            if (itma[0] == 'Provider' || itma[0] == 'User ID' || itma[0] == 'Password' || itma[0] == 'Data Source')
            {
                data[itma[0].replace(" ","")] = itma[1];
            }
        }
    }
    f.Close();
    return data;
}

function file_timestamp()
{
    var t = new Date();
    var t_str = "{0}{1}{2}_{3}{4}{5}".format( t.getFullYear()
                                            , padout(t.getMonth()+1)
                                            , padout(t.getDate())
                                            , padout(t.getHours())
                                            , padout(t.getMinutes())
                                            , padout(t.getSeconds())
                                            );
    return t_str;
}

var msg = "";
try
{
    var isscheduled = fso.FileExists(batchfile);
    if (!isscheduled)
    {
        var udl_data = read_ora_udl();
        var f = fso.OpenTextFile(batchfile, ForWriting, true, tsAscii);
        if (customerId == 'MAD2')
        {
            f.WriteLine("SET sourceUSER=MADE");
        }
        else
        {
            f.WriteLine("SET sourceUSER=" + customerId);
        }
        f.WriteLine("SET targetUSER=" + udl_data['UserID']);
        f.WriteLine("SET targetPASS=" + udl_data.Password);
        var dumpfile = S("refreshfromdumpfile", "").format(customerId);
        if (dumpfile.match(/\.7z$/))
        {
            var path = dumpfile.substring(0, Math.max(dumpfile.lastIndexOf("/"), dumpfile.lastIndexOf("\\")) + 1);
            f.WriteLine("cd /D \"%{0}\"".format(path));
            f.WriteLine("7za  -aoa e {0} >>%0.log 2>>&1".format(dumpfile));
            f.WriteLine("cd /D \"%~dp0\"");
            f.WriteLine("SET deletedmp=1");
            f.WriteLine("ATTRIB -R " + dumpfile.replace(/\.7z$/, "")); // Readonly bitje van de DMP file afhalen
        }
        f.WriteLine("SET dmpfile=" + dumpfile.replace(/\.7z$/, "")); // fclt_LOGC.dmp.7z ==> fclt_LOGC.dmp);
        f.WriteLine("SET targetSERVER=" + udl_data.DataSource);
        f.WriteLine("SET postrefreshsql=" + S("refreshfromdumppostsql", ""));
        f.WriteLine("SET notifyemail=" + emailadr_to);
        f.WriteLine("SET fac_refresh_anon=" + fac_refresh_anon);
        f.WriteLine("SET smtpsendusing=" + S("puo_sendusing"));
        f.WriteLine("SET smtpserver=" + S("puo_smtpserver"));
        f.WriteLine("SET smtpserverport=" + S("puo_smtpserverport"));
        f.WriteLine("SET oracle_login=" + S("refreshfromdump_oracle_login"));
        f.WriteLine("SET mindatabaseschema=" + FCLTMinDatabaseSchema);
        f.WriteLine("SET create_stamp=" + file_timestamp());
        f.WriteLine("autorefreshaccept.bat %0");

        f.Close();

        // In de AiAi logger registreren, zo belangrijk vind ik dit.
        var keeplog = __LogfileName;
        var folder = Server.MapPath(rooturl + "/temp/_AiAi_error");
        var fso = Server.CreateObject("Scripting.FileSystemObject");
        if (!fso.FolderExists(folder))
            fso.CreateFolder(folder);
        var nowtxt = toISODateString(new Date());
        /* global */ __LogfileName = folder + "/log_" + nowtxt + ".html";
        __DoLog("Refresh scheduled for {0}@{1}".format(udl_data['UserID'], udl_data.DataSource), "#f00");
        var dumpfile_timestamp = fso.getFile(dumpfile).DateLastModified;
        __DoLog("Using dump {0} from before {1}".format(dumpfile, toDateTimeString(dumpfile_timestamp)));
        __DoLog("Anonimize option: {0}".format(fac_refresh_anon));
        __DoLog("Notification will be sent to " + emailadr_to);
        __LogfileName = keeplog;
    }
    else
    {
        msg = L("lcl_fac_refresh_exeschedule").format(batchfile);
    }
}
catch(e)
{
    var msg = e.description;
}

var result = { success: (msg == "")
             , message: msg
             };
Response.Write(JSON.stringify(result));
%>
<% ASPPAGE_END(); %>
