#!/usr/bin/env pwsh
#
# INSTALL_TEST_PWSH, pwsh test script for install non-reg suite
# Copyright (C) 2024 Simon Lukas Märtens
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

##########################################################################

param (
   [Parameter(Mandatory)] [string]$initfile,
   [Parameter(ValueFromRemainingArguments)] [string[]] $cmdlist
)

if (-not (Test-Path $initfile)) {
   Write-Error "Cannot read $initfile"
   exit 1
}

# suppress ANSI escape sequences (the errors are rendered in red by default)
$env:__SuppressAnsiEscapeSequences = $true

# source module init file
. $initfile

# execute command list
$code = 0
$runml = 0
$ret = $null
foreach ($cmdargs in $cmdlist.Split(':')) {
   $cmd_is_query = "$cmdargs" -match '(is-loaded|is-avail|is-used|is-saved)'

   # call ml procedure instead of module
   if ($cmdargs -eq 'ml') {
      $runml = 1
      $ret = $null
   } else {
      $cmd_to_execute = ""
      if ($runml -eq 0) {
         $cmd_to_execute += "envmodule"
      } else {
         $cmd_to_execute += "ml"
      }

      # if command equals to NOARG string, means call with no arg passed
      if ($cmdargs -ne 'NOARG') {
         $cmd_to_execute += ' ' + ($cmdargs.Split(',') | ForEach-Object {
            if ($_ -match '[-\s\.$''"]' -or $_ -eq '') {
               if ($_ -match "[']") {
                  '"' + $_ + '"'
               } else {
                  "'" + $_ + "'"
               }
            } else {
               $_
            }
         }) -join ' '
      }

      $ret = Invoke-Expression $cmd_to_execute

      if ($cmd_is_query) {
         $code = [int]!$ret
      } elseif ($LastExitCode -ne 0) {
         $code = $LastExitCode
      }
   }
   if ($null -ne $ret -and !$cmd_is_query) {
      Write-Output $ret
   }
}

Remove-Item -Path "env:__SuppressAnsiEscapeSequences"

exit $code

# vim:set tabstop=3 shiftwidth=3 expandtab autoindent:
