/*
 * Copyright (C) 2010 eCo Software
 * Copyright (C) 2010 Dmitry A.Steklenev
 */

globals = "sys."

if RxFuncQuery( "SysLoadFuncs" ) then do
   call RxFuncAdd "SysLoadFuncs", "RexxUtil", "SysLoadFuncs"
   call SysLoadFuncs
end

parse upper value VALUE( "PATH",, "OS2ENVIRONMENT" ) with "\OS2\SYSTEM" -2,
      sys.boot_disk +2
      
sys.path   = sys.boot_disk"\OS2\DLL"
sys.backup = sys.boot_disk"\OS2\DLL\BACKUP\LXFOCDLG"
sys.script = "filedlgtofocdlg.lxe"
sys.dlls.1 = "PMCTLS.DLL"
sys.dlls.0 = 1
sys.copy.1 = "PMEX.DLL"
sys.copy.0 = 1

parse upper arg make .

if abbrev( "/INSTALL", make, 2 ) then
  return Install()
else if abbrev( "/UNINSTALL", make, 2 ) then
  return UnInstall()
else do
  say "Use /I[NSTALL]   for applying fix,"
  say " or /U[NINSTALL] for removing fix."
end
return 1

/* Applying fix.
 */

Install: procedure expose (globals)

  if DirCreate( sys.backup ) \= 0 then do
     return 2
  end

  do i = 1 to sys.dlls.0
    if stream( sys.backup"\"sys.dlls.i, "C", "QUERY EXIST" ) == "" then do
       if \CopyFile( sys.path"\"sys.dlls.i, sys.backup"\"sys.dlls.i ) then do
          return 3
       end
    end
  end

  do i = 1 to sys.copy.0
    if \CopyFile( sys.copy.i, sys.path"\"sys.copy.i ) then do
       return 4
    end
  end

  do i = 1 to sys.dlls.0
    say "Edit "sys.path"\"sys.dlls.i"..."
    "@lxedit @"sys.script" "sys.path"\"sys.dlls.i
    if rc \= 0 then do
       return 5
    end
  end

  say ""
  say "The fix is applied successfully."
  say "Please restart your system for changes to take effect!"

return 0

/* Removing fix.
 */

UnInstall: procedure expose (globals)

  done = 0

  do i = 1 to sys.dlls.0
    if stream( sys.backup"\"sys.dlls.i, "C", "QUERY EXIST" ) \= "" then do
       if CopyFile( sys.backup"\"sys.dlls.i, sys.path"\"sys.dlls.i ) then do
          "@del "sys.backup"\"sys.dlls.i
          done = done + 1
       end
    end
  end

  if done == sys.dlls.0 then do
     "@rmdir "sys.backup
  end

  say ""
  say "The fix is removed successfully."
  say "Please restart your system for changes to take effect!"

return 0

/* Copy file.
 */

CopyFile: procedure expose (globals)

  parse arg from, to

  "@lxreplace """from"""" """"to""""

  select
    when rc == 0 then
       say "File copied successfully: "  || from
    when rc == 1 then
       say "File copied successfully: "  || from
    otherwise
       say "Error during file copying: " || from || ", rc="rc
  end

return rc == 0 | rc == 1

/* Create directory.
 */

DirCreate: procedure expose (globals)

  parse arg path

  call setlocal
  exist = directory( path )
  call endlocal

  if exist \= "" then do
     return 0
  end

  rc = SysMkDir( path )

  if rc == 3 & pos( "\", path ) \= 0 then do

     parent = left( path, length(path) - pos( "\", reverse(path)))
     rc = DirCreate( parent )

     if rc == 0 then do
        rc = SysMkDir( path )
     end
  end


  if rc \= 0 then do
     say "Unable to create directory: " || path || ", rc="rc
  end
return rc
