/* ExecuteCommand.cmd
 * execute a Suntan Special applicaion
 * writes record to Suntan Special application database appdb.txt
 *
 * Arguments
 *   arg(1) - full path of the application directory
 *   arg(2) - optional arugment
 *
 * Returns
 *   0 - success
 *   1 - failure
 *
 * Copyright (C) 2017 Blonde Guy
 * All Rights Reserved
 */

ApplicationDir = arg(1)
ApplicationCommand = arg(2)

if ApplicationDir = '' then do
   call LogCdi "ExecuteCommand called with empty arg(1)"
   return 1
end

if CheckFiles(ApplicationDir) = 0 then do
   call LogCdi "Missing files in" ApplicationDir
end

appsDir = cdglobal('appsDir')
dbfile = cdglobal('suntanDir') || '\appdb.txt'

call directory ApplicationDir
applicationName = filespec('name', ApplicationDir)
call time 'reset'
beginApp = time('Seconds')
rc = "undefined"
if ApplicationCommand <> '' then do
   call LogCdi "!application Application:" ApplicationName
   apprc = cdi(appsDir, ApplicationCommand)
end
else do
   call LogCdi "!application Application:" ApplicationName
   apprc = cdi(appsDir)
end

if cdglobal('saveWebApps') = 1 then do
   setupDir = cdglobal('setupDir') || '\' || ApplicationName
   if translate(setupDir) <> translate(ApplicationDir) then do
      call LogCdi '!apped SStatus: Saving'
      if copyApp(applicationDir, setupDir) = 0 then do
         call LogCdi "saved" ApplicationName "to" setupDir
      end
   end
end

endApp = time('Seconds')
elapsedTime = endApp - beginApp
call LogCdi applicationName "completed in" elapsedTime "seconds with rc =" apprc
dbfile2 = cdglobal('suntanDir') || '\appdb.txt'
if dbfile <> dbfile2 then do
   call LogCdi "Suntan directory changed by application"
   call LogCdi "Old Suntan directory:" dbfile
   call LogCdi "New Suntan directory:" dbfile2
   dbfile = dbfile2
end

ApplicationDate = getCdiVar('productDate' ApplicationDir || '\cdi.cmd')
call lineout dbfile, date() || ',' ApplicationDir || ',' ApplicationCommand || ',' apprc || ',' ApplicationDate
call LogCdi "!application Application:"

if apprc = 0 then do
   if cdglobal('ShowSuccessDialog') = 1 then do
      productName = getCdiVar('productName' ApplicationDir || '\cdi.cmd')
      cr = d2c(13)
      call MessageDialog "Information", 6, "The command has executed successfully." || cr ||,
                         "Application Name:" ApplicationName || cr ||,
                         "Application Date:" ApplicationDate || cr ||,
                         "Source Directory:" ApplicationDir || cr ||,
                         "Application Command:" ApplicationCommand || cr ||,
                         "Product Name:" productName || cr ||,
                         "Install Dir:" getCdiVar('installDir' ApplicationDir || '\cdi.cmd') || cr ||,
                         "Elapsed Time:" elapsedTime "seconds" || cr || cr ||,
                         "Press OK or wait 10 seconds to dismiss this message." || cr || cr ||,
                         "To disable this dialog, set ShowSuccessDialog to zero."
   end
end

return apprc

CdiDate:

parse arg cdiName

if RxFuncQuery('SysGetFileDateTime') = 0 then do
   return SysGetFileDateTime(cdiName)
end

/* Fallback if SysGetFileDateTime is not found */
call SysFileTree cdiName, 'cdidat.'
if cdidat.0 <> 1 then do
   call LogCdi "Error: CdiDate found" cdidat.0 "files named" cdiName
   return ''
end
mm = left(cdidat.1, 2)
dd = substr(cdidat.1, 4, 2)
yy = substr(cdidat.1, 7, 2)
hh = substr(cdidat.1, 11, 2)
mn = substr(cdidat.1, 14, 2)
if yy < 80 then yy = '20' || yy
else yy = '19' || yy
if left(mm, 1) = ' ' then mm = '0' || right(mm, 1)
if left(hh, 1) = ' ' then hh = '0' || right(hh, 1)
if substr(cdidat.1, 16, 1) = 'p' then hh = hh + 12

return yy || '-' || mm || '-' || dd hh || ':' || mn || ':00'


/* count the number of LogCdi calls in a cdi file
countLogCdi:

parse arg cdiFile

count = 1
do while (lines(cdiFile))
  cdiLine = linein(cdiFile)
  if pos('LogCdi', cdiLine) > 0 then do
     count = count + 1
  end
  if pos('queue', cdiLine) > 0 then do
     count = count + 1
  end
  if pos('EditConfigSys', cdiLine) > 0 then do
     count = count + 2
  end
  if pos('EditFile', cdiLine) > 0 then do
     count = count + 2
  end
end

call stream cdiFile, 'c', 'close'

return count */


CheckFiles:
/*
 * argument application dir containing cdi.cmd
 */

parse arg appDir
fileURL = GetFileURL(appDir || '\cdi.cmd')
if fileURL = '' | fileURL = 0 then return 1
allPartsFound = 1
do while fileURL <> ''
   parse var fileURL partURL ';' fileURL
   fileURL = strip(fileURL,,"'")
   fileURL = strip(fileURL,,'"')
   partURL = strip(partURL)
   partURL = strip(partURL,,'|')
   zTest = pos('F=', partURL)   
   if zTest > 0 then do
      localFile = appDir || '\' || substr(partURL, lastpos('F=', partURL) + 2)
   end
   else do
      localFile = appDir || '\' || substr(partURL, lastpos('/', partURL) + 1)
   end
   if stream(localFile, 'c', 'query exists') = '' then do
      call LogCdi "File not found" localFile
      allPartsFound = 0
   end
end
return allPartsFound

GetFileURL:
/*
 * argument: file to scan for fileURL
 */
parse arg cf
fileURL = getCdiVar('fileURL' cf)
if fileURL = '' then return ''
if right(fileURL,1 ) <> ',' then return fileURL

/* fileURL is multi-line */
fileURL = ''
ffileURL = 0

rc = stream(cf, 'c', 'open read')
if rc <> 'UNKNOWN' & rc <> 'READY:' then do
   call LogCdi "GetFileURL(" || cf || ") error" rc
   return ''
end

do while lines(cf)
   sLine = linein(cf)
   if pos('fileURL =', sLine) > 0 & fileURL = '' then do
      urlLine = ''
      ffileURL = 1
   end
   if ffileURL = 1 then do
      sline = translate(sline,"  ","'"||'"') /* remove quotes */
      urlLine = urlLine || strip(strip(sLine), 'Trailing', ',')
      if right(strip(sLine), 1) <> ',' then do
         parse var urlLine fv '=' fileURL
         ffileURL = 0
      end
   end
end

call stream cf, 'c', 'close'

return fileURL

/* copy application from application dir to setup dir
 * skipping dist and history directories
 */
copyApp:

applicationDir = arg(1)
setupDir = arg(2)

call SysFileTree applicationDir || '\*.*', 'copyd.', 'DO'
do ac = 1 to copyd.0
   capp = substr(copyd.ac, lastpos('\', copyd.ac) + 1)
   if translate(capp) = 'DIST' then iterate
   if translate(capp) = 'HISTORY' then iterate
   address cmd '@xcopy' copyd.ac setupDir || '\' || capp '/s > nul'
   if rc <> 0 then do
      call LogCdi "Error" rc "copying" copyd.ac
      return 1
   end
end

call SysFileTree applicationDir || '\*.*', 'copyf.', 'DO'
do ac = 1 to copyf.0
   address cmd '@copy' copyf.ac setupDir '> nul'
   if rc <> 0 then do
      call LogCdi "Error" rc "copying" copyf.ac
      return 1
   end
end
return 0

/* get Cdi Variable */
getCdiVar:

parse arg myVar myCdiFile

if myVar = '' then do
   call LogCdi "getCdiVar called with no myVar argument"
   return ''
end

if myCdiFile = '' then do
   call LogCdi "getCdiVar called with no myCdiFile argument"
   return ''
end

interpret myVar "=''"

call SysFileSearch myVar, myCdiFile, 'file.'
do i=1 to file.0
   pp = pos(myVar, file.i)
   ep = pos('=', file.i)
   if pp > 0 & pp < ep then do
      if right(file.i, 1) = ',' then do
         return ','
      end
      else do
         interpret file.i
         return value(myVar)
      end
   end
end

return value(myVar)
