/***************************************************/

/*****************************************
* Intialize Rexxutil Functions
******************************************/

  call RxFuncAdd 'SysLoadFuncs' , 'REXXUTIL', 'SysLoadFuncs'

  signal on syntax name MsgExit

  call SysLoadFuncs

  numeric digits 12

/******************************************
* Define message ids from *mid*.h
*******************************************/
  MSG_SYSINIT_BOOT_NOT_FD    = 1475
  MSG_INCORRECT_DOSVER       = 1210
  MSG_NO_META_MATCH          =  257
  MSG_PRINT_FILE_NOT_FOUND   = 1533
  MSG_COMP_INVALID_PATH      = 1171
  MSG_BOOT_MUST_RESTART      = 1716
  MSG_INSTALL_UNSUCCESSFUL   = 1975
  MSG_INSTALL_HY_HDR         = 1976
  MSG_PROC_NOT_FOUND         =  127
  MSG_REP_SOUR_PATH_REQ      = 1137
  MSG_SYS_INV_DRIVE          = 1461
  MSG_CHCP_INVALID_PARAMETER = 1761
  MSG_UNP_INSERT_PI          = 1218
  MSG_ERR_PROC_ARG           = 1249
  MSG_MBS_INVALID_COMMAND    =  872
  SPTReboot                  = x2d('FE00',4)
  SPTRebootErr               = x2d('FE08',4)
  SPTWithErr                 = x2d('0008',4)


/*****************************************
* Initialized globals
******************************************/
  graddPackDSC = 'grdpack.dsc'
  cidInst = ''

/*****************************************
* Set up Source and Target Paths
******************************************/
  parse source one two me
  srcPath = filespec('Drive', me) || filespec('Path', me)
  srcName = filespec('Name', me)

  os2bootPath = SysSearchPath('PATH', 'os2boot')
  if os2bootpath \= ''
   then bootDrive = filespec('drive', os2bootPath)
   else call MsgExit SysGetMessage(MSG_SYSINIT_BOOT_NOT_FD)

/******************************************
* Verify options if any
*******************************************/
  if arg() == 0
    then call Usage
    else do
       cmdline = arg(1)
       parse value(cmdline) with tmp1 '/' option tmp2
       if option \= ''
       then do
          if translate(option) == 'U'
          then do
             cidInst = ' /u /res:640x480x256'
             cmdline = tmp1 || tmp2
          end
          else do
             say MyGetMsg(SysGetMessage(MSG_MBS_INVALID_COMMAND,, '"' || '/' || option || '"'))
             call Usage
          end
       end
       parse value(cmdline) with srcTmp bootTmp junk
       if junk \= '' then call Usage
       dscFile ='intel.dsc' 
       if srcTmp \= ''
         then do
            if filespec('Drive',srcTmp) == strip(srcTmp, 'T', '\')
              then srcChk = srcTmp
              else srcChk = strip(srcTmp, 'T', '\') || '\'
            call SysFileTree srcChk || dscFile, 'file', 'F'
            if file.0 == 0
              then do
                 say MyGetMsg(SysGetMessage(MSG_PRINT_FILE_NOT_FOUND, ,'"' || srcChk || dscFile || '"'))
                 say MyGetMsg(SysGetMessage(MSG_CHCP_INVALID_PARAMETER, ,srcTmp))
                 call Usage
              end
              else srcPath = srcChk
         end
    end

/*****************************************
* Start logging
******************************************/

  installDir = bootDrive || '\os2\install'
  call SysFileTree installDir, 'file', 'D'
  if file.0 == 0 then call MsgExit MyGetMsg(SysGetMessage(MSG_COMP_INVALID_PATH, ,'"' || installDir || '"'))
  logFile = installDir || '\display.log'
  call SysFileTree logFile, 'file', 'F', ,'-----'
  startmsg = MyGetMsg(SysGetMessage(MSG_UNP_INSERT_PI,, SubStr(dscFile,1, pos('.', dscFile)-1 ) ))
  cmd = 'parse value(startmsg) with . '''D2c(10)''' installmsg '''D2c(13)''' junk'
  interpret cmd
  installmsg = strip(installmsg)
  call LogIt '======================================================================'
  say installmsg
  call LogIt installmsg ' - ' Date('L')  Time()
  '@if exist 'srcPath || 'build.lvl type 'srcPath || 'build.lvl >>'logFile


/*******************************************************
* Gradd is not supported on OS/2 Versions less than 3.0
* and it also requires a certain fixpak level for both
* version 3.x and 4.0.  Let us verify we have the right
* levels now.
********************************************************/
  parse value(SysOS2Ver()) with major '.' os2Ver
  rc = 1210
  select
     when major < 2 then call MsgExit MyGetMsg(SysGetMessage(MSG_INCORRECT_DOSVER))
     when datatype(os2Ver) \= 'NUM' then call MsgExit MyGetMsg(SysGetMessage(MSG_INCORRECT_DOSVER))
     when os2Ver < 30  then call MsgExit MyGetMsg(SysGetMessage(MSG_INCORRECT_DOSVER))
     when os2Ver < 40
        then do
           needLevel = 2
           needFPLevel = 8.026
        end
     otherwise
        do
           needLevel = 1
           needFPLevel = 9.029
        end
  end
  parse value(GetGraddLevel(bootDrive || '\os2\dll\gre2vman.dll')) with graddLevel graddStamp
  if \(graddLevel >= needLevel)
  then do         /*  See if we have the right Fixpak Level.  If we do then install anyway */
                  /*  but make sure we lay down the gradd subsystem components             */
     if (GetFPLevel() >= needFPLevel)
     then do
        graddStamp = ''             /* Used later to determine if we need new subsystem comps */
        newStamp   = 1              /* Ditto                                                  */
     end
     else call MsgExit MyGetMsg(SysGetMessage(MSG_INCORRECT_DOSVER))
  end
  rc = 0


/*******************************************************
* Setup path and Copy required files to \os2
********************************************************/

  oldPath = value('PATH', , 'OS2ENVIRONMENT')
  newPath = value('PATH', srcPath || ';' || oldPath, 'OS2ENVIRONMENT')

/********************************************************
* Create .DSP file(s) for particular country
*********************************************************/
  countryCode = GetCountryCode(bootDrive || "\CONFIG.SYS")

/* drw:  cmd = 'copy ' || srcPath || '*.' || countryCode || ' ' || srcPath || '\*.DSP' */
/*  cmd = 'copy ' || srcPath || '*.' || countryCode || ' ' || srcPath || '*.DSP'	*/
/*  call LogIt cmd	*/
/*  '@' || cmd || '>nul 2>&1'	*/

/********************************************************************************* 
* @LRJ 9-3-2001 :											   					 *
*															   					 *
* For Japanese(countryCode=081) or Chinese (countryCode=088) : 					 *
*															   					 *
*	1. 	Check if WinOS2 has also been installed				   					 *
*   2. 	If WINOS2 has not been installed then temporarily 	   					 *
* 		modify the CountryCode for the INTELGRD unpack and	   					 *
*		copy																	 *	
*															   					 *
* This fix is only required for OS2 Version < 4.5 and Fixpack Level < 14.062	 *														   					 
*															   					 *
**********************************************************************************/

  currCountryCode = countryCode
  CountryCodeReplaced = 0

  /* check Japanese or Chinese with no WINOS2 installed, OS2-Version < 45, and FP level < 14.062 */

  if (countryCode = "081" | countryCode = "088") & (\(CheckWinOS2())) & (os2Ver<45) & (GetFPLevel()<14.062) then 
  do
 	countryCode = ReplaceCountryCode(currCountryCode)	/* temporarily modify country code */
    CountryCodeReplaced = 1
  end	


  cmd = 'unpack2 ' || srcPath || 'INTELGRD ' || srcPath || ' /N:intelgrd.' || countryCode
  call LogIt cmd
  '@' || cmd || '>nul 2>&1'

/* RAG 13-03-2000: If unknown country fall back to US-English */
  testname='intelgrd.' || countryCode
  testname = stream(testname, 'c', 'query exists')
  if testname = "" then
  do
	countryCode='001'
    cmd = 'unpack2 ' || srcPath || 'INTELGRD ' || srcPath || ' /N:intelgrd.' || countryCode
    call LogIt cmd
    '@' || cmd || '>nul 2>&1'
  end
/* RAG ENDS */

  cmd = 'copy ' || srcPath || 'intelgrd.' || countryCode || ' ' || srcPath || 'intelgrd.DSP'
  call LogIt cmd
  '@' || cmd || '>nul 2>&1'
  cmd = 'del ' || srcPath || 'intelgrd.' || countryCode
  call LogIt cmd
  '@' || cmd || '>nul 2>&1'

/******************************************************************************* 
*															   				   *
* For Japanese(countryCode=081) or Chinese (countryCode=088) : 				   *
*															   				   *
*	1. 	Check if WinOS2 has also been installed				   				   *
*   2. 	If WINOS2 has not been installed the temporarily 	   				   *
* 		modify the CountryCode for the INTELGRD unpack and	   				   *
*		copy 												   				   *
*															   				   *
*    If the CountryCode has been modified then we need to	   				   *
* 	 restore the original country code here					   				   *
*															   				   *
********************************************************************************/
  
  /* @LRJ 9-3-2001 : Restore original country code if it has been changed */
  if (CountryCodeReplaced) then
  do
	 countryCode = currCountryCode
	 CountryCodeReplaced = 0
  end																	 
	

  cmd = 'unpack2 ' || srcPath || 'COMGRADD ' || srcPath || ' /N:comgradd.' || countryCode
  call LogIt cmd
  '@' || cmd || '>nul 2>&1'
  cmd = 'copy ' || srcPath || 'comgradd.' || countryCode || ' ' || srcPath || 'comgradd.DSP'
  call LogIt cmd
  '@' || cmd || '>nul 2>&1'
  cmd = 'del ' || srcPath || 'comgradd.' || countryCode
  call LogIt cmd
  '@' || cmd || '>nul 2>&1'


/********************************************************
* Obtain .DSC file
*********************************************************/

  call SysFileTree srcPath || dscFile, 'file', 'F'
  if file.0 == 0 then call MsgExit MyGetMsg(SysGetMessage(MSG_PRINT_FILE_NOT_FOUND,, '"' || srcPath || '*.dsc' || '"')),
                                   || MyGetMsg(SysGetMessage(MSG_NO_META_MATCH))
                 else parse value(file.1) with . . . . dscFile

  cmd = 'copy 'dscFile installDir
  dscFile = installDir || '\' || FileSpec('Name', dscFile)
  call LogIt cmd
  '@' || cmd || ' >> 'logfile ' 2>&1'
  if rc \= 0 then call MsgExit ""

  if SysFileTree(bootDrive || '\os2\video.cfg','file','F',,'+****') == 0
    then call SysFileDelete bootDrive || '\os2\video.cfg'

  cmd = 'copy 'srcPath || graddPackDSC installDir
  '@' || cmd || '>nul 2>&1'
  if rc \= 0 then graddPackDSC = ''
             else do
                graddPackDSC = installDir || '\' || graddPackDSC
                parse value(GetGraddLevel(srcPath || 'gre2vman.dll')) with . tmpStamp
                if datatype(tmpStamp) == 'NUM' then newStamp = tmpStamp
             end

  dspInstall = bootDrive || '\os2\install\dspinstl.exe'
  if filespec('Drive', srcPath) \= strip(srcPath, 'T', '\')
    then srcPath = strip(srcPath, 'T', '\')

  if ((symbol('newStamp') == 'VAR') & (newStamp \= ''))
  then do
     if ((graddStamp == '') | ( newStamp > graddStamp))
       then '@' || dspInstall '/pk:other /s:' || srcPath || ' /t:' || bootDrive,
                          || ' /pd:' || strip(graddPackDSC) || ' /l:' || logFile
  end


  '@' || dspInstall '/pk:svga /s:' || srcPath || ' /t:' || bootDrive,
              || ' /pd:' || strip(dscFile) || ' /l:' || logFile || cidInst

/* drw install KBDTEST - Start */
/*  '@' || bootDrive || '\os2\kbdtest.exe -i' */
/* drw install KBDTEST - End */

  if ( (rc == 0) | ((cidInst \= '') & ( rc == SPTReboot)) )
    then call MsgExit MyGetMsg(SysGetMessage(MSG_BOOT_MUST_RESTART))
    else call MsgExit MyGetMsg(SysGetMessage(MSG_ERR_PROC_ARG,,dscFile))

/******************************************************
* GetCountryCode
*
* Returns country code as parsed from CONFIG.SYS
*******************************************************/
GetCountryCode: procedure
parse arg srcFile

    countryCode = "001"

    rc = stream(srcFile, 'C', 'OPEN READ')
    if rc \= "ERROR" then
    do
        do while Lines(srcFile) > 0
            line = StripSpace(Linein(srcFile))
            if Translate(Left(line,8)) = 'COUNTRY=' then
            do
                countryCode = Right(Left(line,11),3)
            end
        end
        rc = stream(srcFile, 'C', CLOSE)
    end

    return countryCode

/******************************************************
* ReplaceCountryCode
*
* Temporarily replace CountryCode 'number number number' 
* 		with    				  'x      number number'
* e.g. 088 becomes x88
*      081 becomes x81
*
* This is used e.g only under the following 2 scenarios
* 1. Japanese WARP installed with no optional English
* 2. Chinese WARP  installed with no optional English
*
* Note: that this is a workaround for an OS2 bug
*
* @LRJ: 9-3-2001
*******************************************************/
ReplaceCountryCode: procedure
parse arg currCountryCode

	NewCountryCode = 'x'||Right(currCountryCode,2)
    return NewCountryCode

/******************************************************
* CheckWinOS2
*
* Check if WINOS2 has been installed.
*
* This function is used for DBCS (Japanese/Chinese)
* Query OS2.INI file in USER mode to check if WINOS2 		
* has been installed 
* 
* This is used e.g only under the following 2 scenarios
* 1. Japanese WARP installed with no optional English
* 2. Chinese WARP  installed with no optional English
*
* Note: that this is a workaround for an OS2 bug
*
* @LRJ: 9-3-2001
*
*
* RETURN VALUE : 1 = WINOS2 installed
*				 0 = WINOS2 not installed
*
*******************************************************/

CheckWinOS2: procedure
	WinOS2Installed = 0

	winos2location=SysIni('USER', 'PM_INSTALL', 'WINOS2_LOCATION')

	/* CHECK IF WINOS2 HAS BEEN INSTALLED */
	if (compare(winos2location,"ERROR:")\=0) then
	do
   		winos2location = SysSearchPath('PATH', 'os2boot')
   		if winos2location \= '' then
   		do
      		/* WINOS2 KEY DETECTED IN OS2.INI WITH ACCEPTABLE PATH */
			WinOS2Installed = 1
   		end
   		else
   		do
      		/* WINOS2 KEY DETECTED IN OS2.INI ... BUT INVALID PATH */
			WinOS2Installed = 0
      		exit
   		end
	end

	else
	do
	  /* WINOS2 HAS NOT BEEN DETECTED */
      WinOS2Installed = 0
	end

    return WinOS2Installed


/******************************************************
* StripSpace
*
* Removes all whitespace from a string
*******************************************************/
StripSpace: procedure
parse arg currText
    do until (endText = "")
        parse var currText beginText ' ' endText
        currText = beginText || endText
    end
    return currText

/******************************************************
* Procedure for determining level of Gradd subsystem
*******************************************************/
GetGraddLevel: Procedure

   parse arg graddModule

   gtvVer = ''

   if stream(graddModule,'c', 'query exists') \= ''
   then do
       newQueue = RxQueue('Create')
       oldQueue = RxQueue('Set', newQueue)
       '@bldlevel 'graddModule '| rxqueue' newQueue
       do while queued() \=0
          parse upper pull tag data
          if tag == 'SIGNATURE:'
          then
             do while queued() \= 0
               parse upper pull tag data
               if tag == 'DESCRIPTION:'
                  then parse value(data) with  'V' gtvVer gtvStamp .
             end
       end
       call RxQueue 'Delete', newQueue
       call RxQueue 'Set', oldQueue
   end

   if datatype(gtvVer)   \= 'NUM' then gtvVer = 0
   if datatype(gtvStamp) \= 'NUM' then gtvStamp = 0

   return gtvVer gtvStamp


/******************************************************
* Procedure for determining fix pack level of system
*******************************************************/
GetFPLevel: Procedure

   newQueue = RxQueue('Create')
   oldQueue = RxQueue('Set', newQueue)
   '@ver /r | rxqueue' newQueue
   do while queued() \=0
      parse upper pull tag data
      if tag == 'REVISION'
      then leave
   end
   call RxQueue 'Delete', newQueue
   call RxQueue 'Set', oldQueue

   return data


/******************************************************
* Error message processing and exit
*******************************************************/
MsgExit:

   parse arg errmsg

   result = rc
   if rc == 43
    then do
        say sigl'  +++      'SourceLine(sigl)
        say 'REX0043: 'ErrorText(43)
    end
    else do
      if errmsg == '' then errmsg = 'REXX' || right(rc,4,'0') || ': 'ErrorText(rc)
      say errmsg
      if ( (rc \= 0) & ((cidInst \= '') & ( rc \= SPTReboot)) )
        then do
           exitmsg = MyGetMsg(SysGetMessage(MSG_INSTALL_UNSUCCESSFUL))
           say exitmsg
        end

      if symbol('logfile') == 'VAR'
        then do
           if symbol('exitmsg') == 'VAR'
             then do
               call LogIt errmsg
               call LogIt exitmsg
               say MyGetMsg(SysGetMessage(MSG_INSTALL_HY_HDR)) || ' ' || logfile
             end
        end
    end
/* 12-04-2000 Change because readme files are now shipped seperately */
/*   if rc == 1210 then '@pause && e  'srcPath || '\readme.txt'        */
   if symbol('oldPath') == 'VAR' then call value 'PATH' , oldPath, 'OS2ENVIRONMENT'
   exit result

/******************************************************
* Safely write to logfile
*******************************************************/
LogIt: Procedure expose logfile

  parse arg message
  call lineout logfile, message
  call stream logfile, 'c', 'close'
  return

/******************************************************
* Remove SYSXXXX: from messages
*******************************************************/
MyGetMsg: Procedure
  parse arg message

  if pos('SYS', word(message, 1)) == 1
    then parse arg . message

  return message

/*****************************************************
* Print usage and exit
******************************************************/
Usage:

      msg = MyGetMsg(SysGetMessage(734,,srcName))
      cmd = 'parse value(msg) with msg '''srcName''' .'
      interpret cmd
      indent = copies(' ',30)
      say msg me || ' ' || srcPath || ' ' || bootDrive || ' [/u]'
      say ''
      exit 1
