/*
 * UPIWIN - Micro Pi Windowing Framework Kernel
 * Copyright (C) 2019 Amy Bowersox/Erbosoft Metaverse Design Solutions
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *-------------------------------------------------------------------------
 */
#include <stdio.h>
#include <string.h>
#include <alloca.h>
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include "scode.h"
#include "config.h"
#include "log.h"
#include "ep_init.h"
#include "ep_util.h"

static wchar_t *python_name = NULL;       /* location of the Python executable */

PyObject *UPIWIN_module = NULL;
PyObject *UPIWIN_tmp_module = NULL;

/* used to link the two modules into Python's init table */
static struct _inittab upiwin_inittab[] = {
  { MOD_NAME_UPIWIN,     Epython_init_upiwin_module     },
  { MOD_NAME_UPIWIN_TMP, Epython_init_upiwin_tmp_module },
  { NULL,                NULL                           }
};

static void epython_cleanup(void)
{
  Py_DECREF(UPIWIN_tmp_module);
  UPIWIN_tmp_module = NULL;
  Py_DECREF(UPIWIN_module);
  UPIWIN_module = NULL;
  Py_FinalizeEx();
  PyMem_RawFree(python_name);
  python_name = NULL;
}

HRESULT Epython_setup(void)
{
  HRESULT hr;
  size_t size;

  python_name = Py_DecodeLocale(Gconfig.python_loc, &size);
  if (!python_name)
  {
    if (size==(size_t)(-1))
    {
      Log(LFATAL, "error allocating Python program location");
      return E_OUTOFMEMORY;
    }
    else
    {
      Log(LFATAL, "internal error in Py_DecodeLocale");
      return E_UNEXPECTED;
    }
  }
  Py_SetProgramName(python_name);

  if (PyImport_ExtendInittab(upiwin_inittab))
  {
    Log(LFATAL, "error allocating extended init table");
    hr = E_OUTOFMEMORY;
    goto error_0;
  }

  Py_Initialize();

  /* Import the modules */
  UPIWIN_module = PyImport_ImportModule(MOD_NAME_UPIWIN);
  if (!UPIWIN_module)
  {
    Log(LFATAL, "error importing the upiwin module");
    hr = Epython_trace_exception();
    goto error_1;
  }
  UPIWIN_tmp_module = PyImport_ImportModule(MOD_NAME_UPIWIN_TMP);
  if (!UPIWIN_tmp_module)
  {
    Log(LFATAL, "error importing the upiwin_tmp module");
    hr = Epython_trace_exception();
    goto error_2;
  }

  hr = Config_exitfunc(epython_cleanup);
  if (FAILED(hr))
    epython_cleanup();
  return hr;

error_2:
  Py_DECREF(UPIWIN_module);
  UPIWIN_module = NULL;
error_1:
  Py_FinalizeEx();
error_0:
  PyMem_RawFree(python_name);
  python_name = NULL;
  return hr;
}

HRESULT Epython_run(void)
{
  HRESULT hr = S_OK;
  int i;
  FILE *fp;
  wchar_t **args;

  Log(LINFO, "Ready to execute %s", Gconfig.script_name);
  fp = fopen(Gconfig.script_name, "rb");
  if (fp)
  {
    args = (wchar_t **)alloca((Gconfig.script_arg_count + 1) * sizeof(wchar_t *));
    memset(args, 0, (Gconfig.script_arg_count + 1) * sizeof(wchar_t *));
    args[0] = Py_DecodeLocale(Gconfig.script_name, NULL);
    if (args[0])
    {
      for (i=0; i<Gconfig.script_arg_count; i++)
      {
        args[i + 1] = Py_DecodeLocale(Gconfig.script_args[i], NULL);
        if (!(args[i + 1]))
        {
          hr = E_OUTOFMEMORY;
          break;
        }
      }
      if (SUCCEEDED(hr))
      {
        PySys_SetArgvEx(Gconfig.script_arg_count + 1, args, 1);
        PyRun_SimpleFile(fp, Gconfig.script_name);
      }
      else
      Log(LERROR, "out of memory running script %s", Gconfig.script_name);
    }
    else
    {
      Log(LERROR, "out of memory running script %s", Gconfig.script_name);
      hr = E_OUTOFMEMORY;
    }
    for (i = 0; i<(Gconfig.script_arg_count + 1); i++)
      if (args[i])
        PyMem_RawFree(args[i]);
    fclose(fp);
  }
  else
  {
    Log(LERROR, "Unable to open script file %s", Gconfig.script_name);
    hr = E_ACCESSDENIED;
  }
  return hr;
}
