// (c) 2006-2007 Electronic Arts Inc.
// gcccmdwrap.cpp : This is a gcc wrapper which reads in parameter files and produces
// one large command line
// Joerg Wagner, YAGER Dev. GmbH
// Thanks for the hints in the PS3 forums

#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <direct.h>
#include <shellapi.h>
#include <iostream>
#include <tchar.h>

int _tmain(int argc, _TCHAR* argv[])
{
    char hugeCMD[65535];
    hugeCMD[0]=0;

    // What we do is:
    // parse the command line
    // if an "@" is found, insert the response file
    // then start gcc with one large command line

    for(int c=0; c<argc; c++)
    {
        // printf("Command line %u is %s\n",c,argv[c]);

        if(c != 0)
        {
            strcat(hugeCMD," ");
        }

        if(*argv[c]=='@')
        {
            FILE *f=fopen(argv[c]+1,"rb");
            fseek(f,0,SEEK_END);
            int size = ftell(f);
            fseek(f,0,SEEK_SET);

            char *buf = new char[size+1];
            fread(buf,size,1,f);
            buf[size]=0;

            fclose(f);
            for(int i=0; i<size;i++)
            {
                if(buf[i]=='\n' || buf[i]=='\r')    buf[i]=' ';
            }
            strcat(hugeCMD,buf);
            delete[] buf;
        }
        else
        {
            // encapsulate every command token with \" \" to make sure tokens containing spaces
            // won't get split by the command processor
            strcat(hugeCMD,"\"");
            strcat(hugeCMD,argv[c]);
            strcat(hugeCMD,"\"");
        }

        if(strlen(hugeCMD) > 32768)
        {
            printf("Error: Command line too long!");
            return 0;
        }
    }

    // printf("\nThe new command line is:\n%s\n##",hugeCMD);
    // build our gcc / ld path

    char gccPath[1024];
    if(GetEnvironmentVariable("CELL_SDK",gccPath,sizeof(gccPath))== 0)
    {
        printf("CELL_SDK not found in environment!");
    }

    if(strstr(argv[0],"-gcc"))
        strcat(gccPath,"\\host-win32\\ppu\\bin\\ppu-lv2-gcc-orig.exe");
    else
    if(strstr(argv[0],"-ld"))
        strcat(gccPath,"\\host-win32\\ppu\\bin\\ppu-lv2-ld-orig.exe");
    else
    if(strstr(argv[0],"ld"))
        strcat(gccPath,"\\host-win32\\ppu\\ppu-lv2\\bin\\ld-orig.exe");

    // get the working dir, so that -I. is beeing evaluated properly
    char workingDir[_MAX_PATH];
    _getcwd(workingDir,sizeof(workingDir));

    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    ZeroMemory( &si, sizeof(si) );
    si.cb = sizeof(si);
    ZeroMemory( &pi, sizeof(pi) );

    // Create the process and copy all handles (stdin/out/err) so we see everything in the
    // same console window
    if(CreateProcess(gccPath,hugeCMD,0,0,TRUE,0,0,workingDir,&si,&pi))
    {
        WaitForSingleObject( pi.hProcess, INFINITE );
        CloseHandle( pi.hProcess );
        CloseHandle( pi.hThread );
    }
    else
    {
        printf("Error code spawning %s is: %u\n",gccPath,GetLastError());
    }

    return 0;
}
