--- pgAgent-NG/job.cpp	2013-09-11 14:20:09.507260538 +0200
+++ pgagent/job.cpp	2013-09-11 12:02:08.412191487 +0200
@@ -11,44 +11,44 @@
 
 #include "pgAgent.h"
 
-#include <sys/types.h>
+#include <wx/file.h>
+#include <wx/filefn.h>
+#include <wx/filename.h>
+#include <wx/process.h>
 
+#include <sys/types.h>
 
 #ifndef __WIN32__
 #include <errno.h>
 #include <sys/wait.h>
 #endif
 
-Job::Job(DBconn *conn, const std::string &jid)
+Job::Job(DBconn *conn, const wxString &jid)
 {
 	threadConn = conn;
 	jobid = jid;
-    status = std::string("");
+	status = wxT("");
 
-    LogMessage(std::string("Starting job: ") + jobid, LOG_DEBUG);
-
-    // every DBconn object has the serviceConnInfo object pointer
-    connInfo* serviceConnInfo = conn->getConnInfo();
+	LogMessage(wxString::Format(_("Starting job: %s"), jobid.c_str()), LOG_DEBUG);
 
 	int rc = threadConn->ExecuteVoid(
-                 std::string("UPDATE pgagent.pga_job SET jobagentid=") + serviceConnInfo->backendPid + std::string(", joblastrun=now() ")+
-                 std::string(" WHERE jobagentid IS NULL AND jobid=") + jobid);
+	             wxT("UPDATE pgagent.pga_job SET jobagentid=") + backendPid + wxT(", joblastrun=now() ")
+	             wxT(" WHERE jobagentid IS NULL AND jobid=") + jobid);
 
 	if (rc == 1)
 	{
-//TODO - Vereinfachung mit RETURNING Clause
-        DBresult *id = threadConn->Execute(
-                           std::string("SELECT nextval('pgagent.pga_joblog_jlgid_seq') AS id"));
+		DBresult *id = threadConn->Execute(
+		                   wxT("SELECT nextval('pgagent.pga_joblog_jlgid_seq') AS id"));
 		if (id)
 		{
-            logid = id->GetString(std::string("id"));
+			logid = id->GetString(wxT("id"));
 
 			DBresult *res = threadConn->Execute(
-                                std::string("INSERT INTO pgagent.pga_joblog(jlgid, jlgjobid, jlgstatus) ")+
-                                std::string("VALUES (") + logid + std::string(", ") + jobid + std::string(", 'r')"));
+			                    wxT("INSERT INTO pgagent.pga_joblog(jlgid, jlgjobid, jlgstatus) ")
+			                    wxT("VALUES (") + logid + wxT(", ") + jobid + wxT(", 'r')"));
 			if (res)
 			{
-                status = std::string("r");
+				status = wxT("r");
 				delete res;
 			}
 			delete id;
@@ -59,60 +59,57 @@
 
 Job::~Job()
 {
-    if (status != std::string(""))
+	if (status != wxT(""))
 	{
 		threadConn->ExecuteVoid(
-            std::string("UPDATE pgagent.pga_joblog ")+
-            std::string("   SET jlgstatus='") + status + std::string("', jlgduration=now() - jlgstart ")+
-            std::string(" WHERE jlgid=") + logid + std::string(";\n")+
-
-            std::string("UPDATE pgagent.pga_job ")+
-            std::string("   SET jobagentid=NULL, jobnextrun=NULL ")+
-            std::string(" WHERE jobid=") + jobid
+		    wxT("UPDATE pgagent.pga_joblog ")
+		    wxT("   SET jlgstatus='") + status + wxT("', jlgduration=now() - jlgstart ")
+		    wxT(" WHERE jlgid=") + logid + wxT(";\n")
+
+		    wxT("UPDATE pgagent.pga_job ")
+		    wxT("   SET jobagentid=NULL, jobnextrun=NULL ")
+		    wxT(" WHERE jobid=") + jobid
 		);
 	}
 	threadConn->Return();
 
-    LogMessage(std::string("Completed job: ") + jobid, LOG_DEBUG);
+	LogMessage(wxString::Format(_("Completed job: %s"), jobid.c_str()), LOG_DEBUG);
 }
 
 
 int Job::Execute()
 {
-    std::ostringstream oss;
-    int rc = 0;
+	int rc = 0;
+	bool succeeded = false;
 	DBresult *steps = threadConn->Execute(
-                          std::string("SELECT * ")+
-                          std::string("  FROM pgagent.pga_jobstep ")+
-                          std::string(" WHERE jstenabled ")+
-                          std::string("   AND jstjobid=") + jobid +
-                          std::string(" ORDER BY jstname, jstid"));
+	                      wxT("SELECT * ")
+	                      wxT("  FROM pgagent.pga_jobstep ")
+	                      wxT(" WHERE jstenabled ")
+	                      wxT("   AND jstjobid=") + jobid +
+	                      wxT(" ORDER BY jstname, jstid"));
 
 	if (!steps)
 	{
-        status = std::string("i");
+		status = wxT("i");
 		return -1;
 	}
-    oss << "Job::Execute() STEPS: " << steps->RowsAffected() << std::endl;
-    LogMessage(oss.str(), LOG_DEBUG);
+
 	while (steps->HasData())
 	{
 		DBconn *stepConn;
-        std::string jslid, stepid, jpecode;
-        std::ostringstream output;
+		wxString jslid, stepid, jpecode, output;
 
-        stepid = steps->GetString(std::string("jstid"));
+		stepid = steps->GetString(wxT("jstid"));
 
-//TODO - Vereinfachung mit RETURNING Clause
 		DBresult *id = threadConn->Execute(
-                           std::string("SELECT nextval('pgagent.pga_jobsteplog_jslid_seq') AS id"));
+		                   wxT("SELECT nextval('pgagent.pga_jobsteplog_jslid_seq') AS id"));
 		if (id)
 		{
-            jslid = id->GetString(std::string("id"));
+			jslid = id->GetString(wxT("id"));
 			DBresult *res = threadConn->Execute(
-                                std::string("INSERT INTO pgagent.pga_jobsteplog(jslid, jsljlgid, jsljstid, jslstatus) ")+
-                                std::string("SELECT ") + jslid + std::string(", ") + logid + std::string(", ") + stepid + std::string(", 'r'")+
-                                std::string("  FROM pgagent.pga_jobstep WHERE jstid=") + stepid);
+			                    wxT("INSERT INTO pgagent.pga_jobsteplog(jslid, jsljlgid, jsljstid, jslstatus) ")
+			                    wxT("SELECT ") + jslid + wxT(", ") + logid + wxT(", ") + stepid + wxT(", 'r'")
+			                    wxT("  FROM pgagent.pga_jobstep WHERE jstid=") + stepid);
 
 			if (res)
 			{
@@ -126,138 +123,129 @@
 
 		if (rc != 1)
 		{
-            status = std::string("i");
+			status = wxT("i");
 			return -1;
 		}
 
-        output.clear();
-        switch ((int) steps->GetString(std::string("jstkind"))[0])
+		switch ((int) steps->GetString(wxT("jstkind"))[0])
 		{
 			case 's':
 			{
-                std::string jstdbname = steps->GetString(std::string("jstdbname"));
-                std::string jstconnstr = steps->GetString(std::string("jstconnstr"));
-
-                // copy connect infos from service connection
-                connInfo* sinfo = new connInfo(threadConn->getConnInfo());
-                // when extra connect_string specified
-                if( !jstconnstr.empty()) sinfo->setConnectionString(jstconnstr);
-                // when extra database specified
-                if( !jstdbname.empty()) sinfo->dbname = jstdbname;
-                LogMessage(std::string("Starting job: ") + jobid + " Connect: "+sinfo->getConnectionString(), LOG_DEBUG);
+				wxString jstdbname = steps->GetString(wxT("jstdbname"));
+				wxString jstconnstr = steps->GetString(wxT("jstconnstr"));
 
-                stepConn = new DBconn(sinfo);
+				stepConn = DBconn::Get(jstconnstr, jstdbname);
 				if (stepConn)
 				{
-                    LogMessage(std::string("Executing SQL step " + stepid + " (part of job " + jobid + ")"), LOG_DEBUG);
-                    rc = stepConn->ExecuteVoid(steps->GetString(std::string("jstcode")));
-                    LogMessage(std::string("Executed SQL step " + stepid + " (Err-Meldung: " + stepConn->GetLastError() + ")"), LOG_DEBUG);
-                    output <<  stepConn->GetLastError();
+					LogMessage(wxString::Format(_("Executing SQL step %s (part of job %s)"), stepid.c_str(), jobid.c_str()), LOG_DEBUG);
+					rc = stepConn->ExecuteVoid(steps->GetString(wxT("jstcode")));
+					succeeded = stepConn->LastCommandOk();
+					output = stepConn->GetLastError();
 					stepConn->Return();
-                    delete stepConn;
 				}
 				else
 				{
-                    output << ("Couldn't get a connection to the database!");
-					rc = -1;
+					output = _("Couldn't get a connection to the database!");
+					succeeded = false;
 				}
 
+
 				break;
 			}
-            case 'b':
+			case 'b':
 			{
 				// Batch jobs are more complex thank SQL, for obvious reasons...
-            LogMessage(std::string("Executing batch step " + stepid + " (part of job " + jobid + ")"), LOG_DEBUG);
+				LogMessage(wxString::Format(_("Executing batch step %s (part of job %s)"), stepid.c_str(), jobid.c_str()), LOG_DEBUG);
 
 				// Get a temporary filename, then reuse it to create an empty directory.
-                std::string dirname = CreateTempFileName(std::string("pga_"));
-                if (dirname.empty())
+				wxString dirname = wxFileName::CreateTempFileName(wxT("pga_"));
+				if (dirname.Length() == 0)
 				{
-                    output.clear();
-                    output << ("Couldn't get a temporary filename!");
-                    LogMessage(output.str(), LOG_WARNING);
+					output = _("Couldn't get a temporary filename!");
+					LogMessage(_("Couldn't get a temporary filename!"), LOG_WARNING);
 					rc = -1;
 					break;
 				}
 
-                if (RemoveFile(dirname) != 0)
+				;
+				if (!wxRemoveFile(dirname))
 				{
-                    output <<  "Couldn't remove temporary file: " << dirname << std::endl;
-                    LogMessage(output.str(), LOG_WARNING);
+					output.Printf(_("Couldn't remove temporary file: %s"), dirname.c_str());
+					LogMessage(output, LOG_WARNING);
 					rc = -1;
 					break;
 				}
 
-                if (Mkdir(dirname, 0700) != 0)
+				if (!wxMkdir(dirname, 0700))
 				{
-                    output << "Couldn't create temporary directory: " << dirname << std::endl;
-                    LogMessage(output.str(), LOG_WARNING);
+					output.Printf(_("Couldn't create temporary directory: %s"), dirname.c_str());
+					LogMessage(output, LOG_WARNING);
 					rc = -1;
 					break;
 				}
 
 #ifdef __WIN32__
-                std::string filename = dirname + std::string("\\") + jobid + std::string("_") + stepid + std::string(".bat");
+				wxString filename = dirname + wxT("\\") + jobid + wxT("_") + stepid + wxT(".bat");
 #else
-                std::string filename = dirname + std::string("/") + jobid + std::string("_") + stepid + std::string(".scr");
+				wxString filename = dirname + wxT("/") + jobid + wxT("_") + stepid + wxT(".scr");
 #endif
 
 				// Write the script
-                std::ofstream of(filename);
+				wxFile *file = new wxFile();
 
-                if(!of.is_open())
+				if (!file->Create(filename, true, wxS_IRUSR | wxS_IWUSR | wxS_IXUSR))
 				{
-                    output << "Couldn't open temporary script file: " << filename << std::endl;
-                    LogMessage(output.str(), LOG_WARNING);
-                    RemoveFile(filename);
-                    Rmdir(dirname);
+					output.Printf(_("Couldn't create temporary script file: %s"), filename.c_str());
+					LogMessage(output, LOG_WARNING);
 					rc = -1;
 					break;
 				}
 
-                if (Chmod(filename, 0700) !=0 )
-                {
-                    output << "Couldn't create temporary script file: " << filename << std::endl;
-                    LogMessage(output.str(), LOG_WARNING);
-                    rc = -1;
-                    break;
-                }
-                std::string code = steps->GetString(std::string("jstcode"));
+				if (!file->Open(filename, wxFile::write))
+				{
+					output.Printf(_("Couldn't open temporary script file: %s"), filename.c_str());
+					LogMessage(output, LOG_WARNING);
+					wxRemoveFile(filename);
+					wxRmdir(dirname);
+					rc = -1;
+					break;
+				}
+
+				wxString code = steps->GetString(wxT("jstcode"));
 
 				// Cleanup the code. If we're on Windows, we need to make all line ends \r\n,
 				// If we're on Unix, we need \n
-                ReplaceString(code, std::string("\r\n"), std::string("\n"));
+				code.Replace(wxT("\r\n"), wxT("\n"));
 #ifdef __WIN32__
-                ReplaceString(code, std::string("\n"), std::string("\r\n"));
+				code.Replace(wxT("\n"), wxT("\r\n"));
 #endif
 
-                //if (!file->Write(code))
-                if(!of.good())
+				if (!file->Write(code))
 				{
-                    output << "Couldn't write to temporary script file: " << filename << std::endl;
-                    LogMessage(output.str(), LOG_WARNING);
-                    RemoveFile(filename);
-                    Rmdir(dirname);
+					output.Printf(_("Couldn't write to temporary script file: %s"), filename.c_str());
+					LogMessage(output, LOG_WARNING);
+					wxRemoveFile(filename);
+					wxRmdir(dirname);
 					rc = -1;
 					break;
-                }
-                of << code;
-                of.close();
+				}
 
-                LogMessage(std::string("Executing script file: ") + filename, LOG_DEBUG);
+				file->Close();
+				LogMessage(wxString::Format(_("Executing script file: %s"), filename.c_str()), LOG_DEBUG);
 
 				// Execute the file and capture the output
 #ifdef __WIN32__
 				// The Windows way
-				HANDLE h_script;
+				HANDLE h_script, h_process;
 				DWORD dwRead;
 				char chBuf[4098];
 
-				h_script = win32_popen_r(filename.wc_str());
+				h_script = win32_popen_r(filename.wc_str(), h_process);
 				if (!h_script)
 				{
-                    output << "Couldn't execute script: " << filename << ", GetLastError() returned " << GetLastError() << ", errno = " << errno << "" << std::endl;
-                    LogMessage(output.str(), LOG_WARNING);
+					output.Printf(_("Couldn't execute script: %s, GetLastError() returned %d, errno = %d"), filename.c_str(), GetLastError(), errno);
+					LogMessage(output, LOG_WARNING);
+					CloseHandle(h_process);
 					rc = -1;
 					break;
 				}
@@ -272,24 +260,25 @@
 							break;
 
 						chBuf[dwRead] = 0;
-                        output << (chBuf);
+						output += wxString::FromAscii(chBuf);
 					}
 				}
 
 
+				GetExitCodeProcess(h_process, (LPDWORD)&rc);
+				CloseHandle(h_process);
 				CloseHandle(h_script);
-				rc = 1;
 
 #else
 				// The *nix way.
 				FILE *fp_script;
 				char buf[4098];
 
-                fp_script = popen(filename.c_str(), "r");
+				fp_script = popen(filename.mb_str(wxConvUTF8), "r");
 				if (!fp_script)
 				{
-                    output << "Couldn't execute script: " << filename << ", errno = " << errno << std::endl;
-                    LogMessage(output.str(), LOG_WARNING);
+					output.Printf(_("Couldn't execute script: %s, errno = %d"), filename.c_str(), errno);
+					LogMessage(output, LOG_WARNING);
 					rc = -1;
 					break;
 				}
@@ -298,7 +287,7 @@
 				while(!feof(fp_script))
 				{
 					if (fgets(buf, 4096, fp_script) != NULL)
-                        output << (buf);
+						output += wxString::FromAscii(buf);
 				}
 
 				rc = pclose(fp_script);
@@ -307,112 +296,97 @@
 					rc = WEXITSTATUS(rc);
 				else
 					rc = -1;
+
 #endif
 
-				// Delete the file/directory. If we fail, don't overwrite the script output in the log, just throw warnings.
+				// set success status for batch runs, be pessimistic by default
+				LogMessage(wxString::Format(_("Script return code: %d"), rc), LOG_DEBUG);
+				if (rc == 0)
+					succeeded = true;
 
-                if (RemoveFile(filename) != 0)
+				// Delete the file/directory. If we fail, don't overwrite the script output in the log, just throw warnings.
+				if (!wxRemoveFile(filename))
 				{
-                    LogMessage(std::string("Couldn't remove temporary script file: ") + filename, LOG_WARNING);
+					LogMessage(wxString::Format(_("Couldn't remove temporary script file: %s"), filename.c_str()), LOG_WARNING);
+					wxRmdir(dirname);
 					break;
-                }
+				}
 
-                if (Rmdir(dirname) != 0)
+				if (!wxRmdir(dirname))
 				{
-                    LogMessage(std::string("Couldn't remove temporary directory: ")+ dirname, LOG_WARNING);
+					LogMessage(wxString::Format(_("Couldn't remove temporary directory: "), dirname.c_str()), LOG_WARNING);
 					break;
 				}
 
 				break;
 			}
-
-            default:
+			default:
 			{
-                output << ("Invalid step type!");
-                status = std::string("i");
+				output = _("Invalid step type!");
+				status = wxT("i");
 				return -1;
 			}
 		}
 
-        std::string stepstatus;
-		if (rc == 0)
-            stepstatus = std::string("s");
+		wxString stepstatus;
+		if (succeeded)
+			stepstatus = wxT("s");
 		else
-            stepstatus = steps->GetString(std::string("jstonerror"));
+			stepstatus = steps->GetString(wxT("jstonerror"));
 
-        std::ostringstream oss;
-        oss << std::string("UPDATE pgagent.pga_jobsteplog ");
-        oss << std::string("   SET jslduration = now() - jslstart, ");
-        oss << std::string("       jslresult = ") << rc << std::string(", jslstatus = '") <<  stepstatus + std::string("', ");
-        oss << std::string("       jsloutput = ") << threadConn->qtDbString(output.str());
-        oss << std::string(" ") << std::string(" WHERE jslid=") << jslid;
-        rc = threadConn->ExecuteVoid(oss.str());
-        if (rc != 1 || stepstatus == std::string("f"))
+		rc = threadConn->ExecuteVoid(
+		         wxT("UPDATE pgagent.pga_jobsteplog ")
+		         wxT("   SET jslduration = now() - jslstart, ")
+		         wxT("       jslresult = ") + NumToStr(rc) + wxT(", jslstatus = '") + stepstatus + wxT("', ")
+		         wxT("       jsloutput = ") + threadConn->qtDbString(output) + wxT(" ")
+		         wxT(" WHERE jslid=") + jslid);
+		if (rc != 1 || stepstatus == wxT("f"))
 		{
-            status = std::string("f");
-            LogMessage(std::string("ERROR: UPDATE STEP STATUS Stepstatus=")+stepstatus, LOG_DEBUG);
+			status = wxT("f");
 			return -1;
 		}
-        LogMessage(std::string("steps->MoveNext()"), LOG_DEBUG);
 		steps->MoveNext();
 	}
 	delete steps;
 
-    status = std::string("s");
+	status = wxT("s");
 	return 0;
 }
 
-JobThread::JobThread(const std::string &jid, connInfo* serviceConnInfo)
+
+
+JobThread::JobThread(const wxString &jid)
+	: wxThread(wxTHREAD_DETACHED)
 {
-    LogMessage(std::string("JobThread(const std::string &jid, connInfo* serviceConnInfo) job thread job ") + jid, LOG_DEBUG);
+	LogMessage(wxString::Format(_("Creating job thread for job %s"), jid.c_str()), LOG_DEBUG);
 
 	runnable = false;
 	jobid = jid;
 
-    thConn = new DBconn(serviceConnInfo);
-    if (thConn)
+	DBconn *threadConn = DBconn::Get(DBconn::GetBasicConnectString(), serviceDBname);
+	if (threadConn)
 	{
-        job = new Job(thConn, jobid);
+		job = new Job(threadConn, jobid);
 
 		if (job->Runnable())
 			runnable = true;
-            m_stop = false;
 	}
 }
 
 
 JobThread::~JobThread()
 {
-  try {
-    stop();
-    LogMessage(std::string("Destroying job thread for job ") + jobid, LOG_DEBUG);
-    delete job;
-    delete thConn;
-  } catch(...) { LogMessage(std::string("Destroying job thread for job ") + jobid, LOG_ERROR); }
+	LogMessage(wxString::Format(_("Destroying job thread for job %s"), jobid.c_str()), LOG_DEBUG);
 }
 
-void JobThread::run()
-{
-    if (!m_stop) { // if statt while
-        std::cout << "JobThread::run() - Job execute" << std::endl;
-        job->Execute();
-        m_stop = false;
-    };
-}
 
-void JobThread::stop()
+void *JobThread::Entry()
 {
-    m_stop = true; m_thread.join();
-}
-
-void JobThread::start()
-{
-    std::cout << "JobThread::start()" << std::endl;
-    m_thread = std::thread(&JobThread::run, this);
-}
+	if (runnable)
+	{
+		job->Execute();
+		delete job;
+	}
 
-bool JobThread::finished()
-{
-    if(!m_stop) return true;
-    else return false;
+	return(NULL);
 }
