/* 
   read boot config.sys
*/

#define INCL_DOSPROCESS  /* DOS thread and process values */
#define INCL_DOSERRORS   /* DOS error values */
#define INCL_DOSMISC     /* DOS Miscellaneous values */
#include <os2.h>
#include <stdio.h>
#include <string.h>
#include <ddk/os2sysctl.h>

#define ALLOC_SIZE    65536

APIRET APIENTRY DosSysCtl(ULONG func, PULONG p);

int main(int argc, char *argv[]) {
   APIRET      rc;
   ULONG      res;
   HFILE     file;
   PULONG    data;

   if (argc<2) {
      printf("usage: getconfig <output_file>\n");
      return 1;
   }
   if (DosQuerySysInfo(33L,33L,(PVOID)&res,sizeof(ULONG))!=NO_ERROR) {
      printf("Warning! IBM kernels support config read in two disk boot mode only!\n");
   } else 
   if (res<2425) {
      printf("Warning! Too old OS/4 svn revision. At least 2425 required!\n");
   }

   if (DosAllocMem((PVOID*)&data,ALLOC_SIZE,PAG_COMMIT|PAG_READ|PAG_WRITE)) {
      printf("failed to alloc\n");
      return 2;
   }
   *data = 0;
   if ((rc = DosSysCtl(SYS_GETCONFIGSYS, data))) { 
      printf ("DosSysCtl: rc=%d\n",rc); 
      return 3; 
   }
   if (!*data||*data>ALLOC_SIZE-4) { 
      printf ("DosSysCtl: invalid data\n"); 
      return 4; 
   }
   if (stricmp(argv[1],"con")==0) file = 1; 
      else
   if (DosOpen(argv[1],&file,&res,0,FILE_ARCHIVED,OPEN_ACTION_CREATE_IF_NEW|
      OPEN_ACTION_REPLACE_IF_EXISTS,OPEN_ACCESS_READWRITE|OPEN_SHARE_DENYWRITE,0))
   {
      printf("failed to create \"%s\"\n",argv[1]);
      return 5;
   }
   DosWrite(file,data+1,*data,&res);
   if (res!=*data) {
      printf("failed to write \"%s\"\n",argv[1]);
      return 6;
   }
   DosFreeMem(data);
   if (file!=1) DosClose(file);
   return 0;
}
