// mysql-backup.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <string>
#include <iostream>

static void setup_python(int argc, char **argv)
{
  size_t bufsize;
  char *pathlist = NULL;
  TCHAR szPath[MAX_PATH];
  std::string module_path;
  if( GetModuleFileName( NULL, szPath, MAX_PATH ) )
  {
    CHAR char_path[MAX_PATH]= {0};
    WideCharToMultiByte(CP_UTF8, 0, szPath, -1, char_path, MAX_PATH, NULL, NULL);
    std::string full_path(char_path);
    size_t path_end = full_path.find_last_of('\\');
    if (path_end != std::string::npos)
    {
      module_path = full_path.substr(0,path_end+1);
    }
  }

#if 0
  if (_dupenv_s(&pathlist, &bufsize, "PYTHONPATH") == 0 && pathlist)
  {
    int len = strlen("PYTHONPATH")+1+strlen(pathlist)+strlen(";python;scripts")+1;
    char *tmp = (char*)malloc(len);
    sprintf_s(tmp, len, "PYTHONPATH=%s;python;scripts", pathlist);
    _putenv(tmp);
    free(tmp);
  }
  else
#endif

      SetDllDirectoryA((module_path + "..").c_str());

//     std::string pythonpath("PYTHONPATH=");
//This should intialize PYTHONPATH, but for some reason it doesn't work when built in VS2010
     std::string pythonpath;
     pythonpath.append(module_path).append("scripts;");
     pythonpath.append(module_path).append("..\\python\\mysql_libs.zip;");
     pythonpath.append(module_path).append("..\\python");
//     _putenv_s("PYTHONPATH","");
     _putenv_s("PYTHONHOME","..\\python");
     _putenv_s("PYTHONPATH",pythonpath.c_str());
//     _dupenv_s(&pathlist, &bufsize, "PYTHONPATH");
//     printf(pathlist);printf("\n");
    //_putenv(pythonpath.c_str());
  if (pathlist) free(pathlist);

  Py_SetProgramName(argv[0]);
// Here comes some ugly hack to fix PYTHONPATH init problem
// Create dummy site package to avoid error import site message from Py_Initialize();
  FILE * pFile;
  pFile = fopen ("site.py","w");
  if (pFile!=NULL)
    fclose (pFile);

  Py_Initialize();//Initialize Python
  
  //Delete dummy site module
  remove("site.py");
  remove("site.pyc");

  PySys_SetArgv(argc, argv);

  //Now import sys and modify PYTHONPATH
  PyRun_SimpleString("import sys");
//  PyRun_SimpleString("print sys.path");
  PyRun_SimpleString("sys.path.append('scripts')");
  PyRun_SimpleString("sys.path.append('..\\python\\mysql_libs.zip')");
  PyRun_SimpleString("sys.path.append('..\\python')");
  //reload site module with real module from updated PYTHONPATH
  PyRun_SimpleString("import site");
  PyRun_SimpleString("reload(site)");
//  PyRun_SimpleString("import os");
//  PyRun_SimpleString("print os.environ['PYTHONPATH']");

//  PyRun_SimpleString("print sys.path");
//  PyRun_SimpleString("from sys import exit");
//  PyRun_SimpleString("print '!!!!!!!!!!!!!!!!!!!!!!!'");
  //PyRun_SimpleString("import os");
  //PyRun_SimpleString("os.putenv('PYTHONPATH', 'scripts')");
}


static void finalize_python()
{
  Py_Finalize();
}


static int import_and_call_module(const char *name)
{

   PyObject *main = PyImport_AddModule("__main__");
  PyObject *globals;
  PyObject *module = PyImport_ImportModule(name);
  int main_name_len;
  char *main_name;
  if (!main || !module)
  {
    PyErr_Print();
    fprintf(stderr, "Unable to start %s, please verify that your installation is correct\n",
      name);
    return -1;
  }

  globals = PyModule_GetDict(main);
  if (!globals)
  {
    PyErr_Print();
    fprintf(stderr, "Unable to start %s, please verify that your installation is correct\n",
      name);
    return -1;
  }

  PyDict_SetItemString(globals, name, module);

  main_name_len = strlen(name)+strlen("_main()")+2;
  main_name = (char*)malloc(main_name_len);
  if (!main_name)
  {
    fprintf(stderr, "Out of memory\n");
    return -1;
  }

#ifdef _WIN32
  sprintf_s(main_name, main_name_len, "%s._main()", name);
#else
  snprintf(main_name, main_name_len, "%s._main()", name);
#endif
  // call the _main() function from the module
  PyObject *result = PyRun_String(main_name, Py_eval_input, globals, globals);
  if (!result)
  {
    free(main_name);
    PyErr_Print();
    fprintf(stderr, "Error executing %s, please verify that your installation is correct\n",
      name);
    return -1;
  }

  free(main_name);

  // result is the return code
  return (int)PyInt_AsLong(result);

//  PyObject *module = PyImport_ImportModule(name);
  return 0;

  //PyObject *module = PyImport_ImportModule(name);
  PyObject* localDict;
  PyObject* globalDict;
  localDict = PyDict_New();
  globalDict = PyDict_New();
  PyObject* mainModule;
  PyObject* mainModuleDict;

  mainModule=PyImport_AddModule("__main__");
  if(mainModule==NULL) { }

  mainModuleDict=PyModule_GetDict(mainModule);
  FILE *fpIn = fopen (name, "r+");
  PyObject* tempPyResult = PyRun_File(fpIn,name,0,mainModuleDict,localDict);
  return 0;
}



int main(int argc, char* argv[])
{
  int rc;

  setup_python(argc, argv);

  std::string filepath(argv[0]);
  size_t name_start = filepath.find_last_of('\\');
  if (name_start == std::string::npos)
    name_start = 0;
  else
    ++name_start;
  size_t name_end = filepath.find_last_of('.');
  size_t name_size = name_end - name_start;
  if (name_size < 0)
    name_size = std::string::npos;
  std::string filename = filepath.substr(name_start,name_size);
  //filename.append(".py");
  //std::cout<<filename<<std::endl;
  rc = import_and_call_module(filename.c_str());
  
  finalize_python();

  return rc;
}

