/*
    Example code to show how to programmatically pass cmds
    to CESH
*/
#include <windows.h>
#include <stdio.h>
#include <io.h>
#include <fcntl.h>


int main(int argc, char **argv)
{
    char szFSAUXIN[_MAX_PATH];
    char szCmd[_MAX_PATH] = {0};

    // catenate the cmd into a single string up to the max length
    if ( argc > 1 )
    {
        int iCurCmdLen = 0;

        for ( int i = 1; i < argc; i++ )
        {
            if ( (iCurCmdLen + strlen(argv[i]) + 2) > _MAX_PATH-1 )
            {
                printf("Error: cmd string is too long. "
                       "Max size is %d\n", _MAX_PATH-1);
                exit(EXIT_FAILURE);
            }

            sprintf(&szCmd[iCurCmdLen], "%s ", argv[i]);
            iCurCmdLen += strlen(argv[i]) + 1;
        }

        strcat(szCmd, "\r");
    }
    else
    {
        printf("syntax: ceshexec <cmd>\n");
        exit(EXIT_FAILURE);
    }

    // make sure we have a _FLATRELEASEDIR
    LPCSTR pcszFRD = getenv("_FLATRELEASEDIR");
    if ( !pcszFRD )
    {
        printf("Error: Environment variable "
               "_FLATRELEASEDIR must be set\n");
        exit(EXIT_FAILURE);
    }

    // build path to FSAUXIN, avoiding double slashes
    if ( pcszFRD[strlen(pcszFRD)-1] != '\\' )
        sprintf(szFSAUXIN, "%s\\fsauxin", pcszFRD);
    else
        sprintf(szFSAUXIN, "%sfsauxin", pcszFRD);


    int fh = open(szFSAUXIN,  _O_WRONLY | _O_APPEND);
    if ( fh != -1 )
    {
        write(fh, szCmd, strlen(szCmd));
        close(fh);
    }
    else
        printf("Error: could not open '%s'\n", szFSAUXIN);

    return 0;
}

