/**
 * setup.cpp :
 * invokes corresponding replicatorreceivercd?.jnlp file when invoked from a CD
 * setup.exe usually trigged by autorun.inf
 * Need a different version depending on which drive letter is the CD ROM drive.
 * For windows only.
 *
 * Copyright: (c) 2003-2017 Roedy Green, Canadian Mind Products
 * #101 - 2536 Wark Street
 * Victoria, BC Canada V8T 4G8
 * tel:(250) 361-9093
 * http://mindprod.com
 */

#include "stdafx.h"  /* standard precompiled header */

#include <direct.h>  /* chdir, mkdir */
#include <process.h> /* exec, spawn */
#include <stdio.h>   /* fclose, fgetc, printf, remove, rename, setvbuf */
#include <stdlib.h>  /* exit, putenv, _splitpath */
#include <string.h>  /* strcpy, strcat, strcmp, strupr */

/* Configure root name of all the jnlp files we might invoke */
const char* jnlpBaseName = "replicatorreceivercd";

/**
 * Invoke JNLP file corresponding to drive letter
 * running from.
 *
 * @param argc   not used
 * @param argv   not used
 *
 * @return system error code
 */
int main( int argc, char* argv[] )
   {
   // get current drive letter, the CD-ROM drive letter.
   char curDrive = 'A' +  _getdrive() - 1;

   // generate name of jnlp file corresponding to CD drive letter
   // e.g. replicatorreceiverR.jnlp
   int baseLength = strlen( jnlpBaseName );
   char* jnlpName = new char[ baseLength + 7];
   strcpy( jnlpName, jnlpBaseName );
   // tack on drive letter A..Z
   jnlpName[ baseLength ] = curDrive;
   jnlpName[ baseLength + 1 ] = 0;
   strcat ( jnlpName, ".jnlp" );

   // Java webstart is usually in
   // C:\Program Files\Java\j2re1.4.2_06\javaws\javaws.exe
   // but we can't count on it.
   // Find command processor shell that knows jnlp-to-javaws.exe association.
   // Shell usually c:\winnt\system32\cmd.exe though
   // might be 4NT.exe or COMMAND.COM
   char* shell = getenv( "ComSpec" );
   if ( shell == NULL )
      {
      shell = "cmd.exe";
      }

   printf( "Installing %s with Java Web Start via the %s shell.\n", jnlpName, shell );

   // This won't work if the *.jnlp -> javaws.exe association is broken.

   // start up Java Web Start with, for example, replicatorreceiverR.jnlp.
   if ( _spawnlp( _P_OVERLAY, shell, shell, "/C", jnlpName, NULL ) )
      {
      // ENOENT = 2 = not found
      // EINVAL = 22 = invalid arg
      printf ( "Java Web Start, part of the Java JRE, must be installed first.  Error %u\n", errno );
      }
   delete jnlpName;
   return 0;
   }