/* (C) 2003-2007 Willem Jan Hengeveld <itsme@xs4all.nl>
 * Web: http://www.xs4all.nl/~itsme/
 *      http://wiki.xda-developers.com/
 *
 * $Id$
 */
#include <util/wintypes.h>

#include <stdio.h>
#include <string.h>
#include <util/rapitypes.h>

#include <string>
#include "stringutils.h"
#include "debug.h"
#include "csidlpaths.h"
#include "checkdll.h"
#include "dllversion.h"
#include "itsutils.h"

// todo:
//    DONE: add '-w'  option to wait ( a maximum ) time for the execution to finish
//    ... implement this by calling itsutils.dll ITRunProcess
//    ...    which should WaitForSingleObject on the process handle
//
//    add '-e' option to use 'shellExecute' to 'open' the parameter
//    add '-b VERB'  to specify the shellexecute verb

DWORD ITWaitForProcess(DWORD dwProcessHandle);

// ... windows quoting rules are a bit foggy, hope i get it right here.
std::string quote(const std::string& str)
{
    std::string qstr = "\"";
    for (size_t i=0 ; i<str.size() ; i++)
    {
        if (str[i]=='\"')
            qstr += "\\";
        qstr += str[i];
    }

    qstr += "\"";

    return qstr;
}
std::string basename(const std::string& str)
{
    size_t lastslash= str.find_last_of("\\/");
    if (lastslash==std::string::npos)
        return str;
    
    return str.substr(lastslash+1);
}
void usage()
{
    printf("(C) 2003-2008 Willem jan Hengeveld  itsme@xs4all.nl\n");
    printf("Usage: prun [-w] [-c] exepath [arguments]\n");
    printf("    -w   : wait for process to terminate\n");
    printf("    -c   : copy exe to device before executing it\n");
    printf("    -o   : exepath is opened using the shell\n");
}
int main( int argc, char *argv[])
{
    int res= 0;
    DebugStdOut();

    bool bWaitForExit= false;
    bool bCopyToDevice= false;
    bool bOpenWithShell= false;
    bool bBase64Encoded= false;

    std::string cmd;
    std::string args;
    for (int i=1 ; i<argc ; i++)
    {
        // prun options must preceed the command
        if (cmd.empty() && argv[i][0]=='-') switch(argv[i][1])
        {
            case 'w': bWaitForExit= true; break;
            case 'c': bCopyToDevice= true; break;
            case 'o': bOpenWithShell= true; break;
            case 'b': bBase64Encoded= true; break;
            default:
                      usage();
                      return 1;
        }
        else if (cmd.empty()) {
            cmd=argv[i];
        }
        else {
            if (!args.empty())
                args += " ";
            std::string arg= argv[i];
            if (arg.find(' ')!=std::string::npos) {
                args += quote(arg);
            }
            else {
                args += arg;
            }
        }
    }
    if (cmd.empty())
    {
        printf("no command specified\n");
        usage();
        return 1;
    }

    if (bWaitForExit||bOpenWithShell)
        CheckITSDll();
    else if (FAILED(CeRapiInit()))
    {
        error("initializing rapi");
        return 1;
    }

    if (bCopyToDevice) {
        std::string dst= std::string("%CSIDL_WINDOWS%\\")+basename(cmd);
        
        if (!CeCopyFileToDevice(cmd, ToString(expand_csidl(ToWString(dst))), true)) {
            res= 1;
        }
        cmd = dst;
    }
    PROCESS_INFORMATION pi;
    memset(&pi, 0, sizeof(pi));
    if (bBase64Encoded)
    {
        ByteVector data = base64_decode(args);

        args.resize(data.size());
        for (unsigned i=0 ; i<data.size() ; i++)
            args[i]=data[i];
    }
    if (!res && !CeCreateProcess( expand_csidl(ToWString(cmd)).c_str(), ToWString(args).c_str(),
            NULL, NULL, FALSE, 0, NULL, NULL, NULL,
            &pi))
    {
        ceerror("CreateProcess failed with Errorcode = %ld\n", CeGetLastError());
        res= 1;
    }
    else
    {
        if (bWaitForExit && pi.hProcess)
            res= ITWaitForProcess((DWORD)pi.hProcess);
        CeCloseHandle( pi.hProcess);
        CeCloseHandle( pi.hThread);
    }

    StopItsutils();

    return res;
}

DWORD ITWaitForProcess(DWORD dwProcessHandle)
{
    WaitForProcessParams*inbuf=NULL;
    DWORD insize= sizeof(WaitForProcessParams);
    inbuf= (WaitForProcessParams*)RapiAlloc(insize);
    DWORD outsize=0;

    inbuf->dwProcessHandle= dwProcessHandle;

    HRESULT res= ItsutilsInvoke("ITWaitForProcess",
            insize, (BYTE*)inbuf,
            &outsize, NULL);
    return res;
}

