# serviceHelper.ps1

$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Definition
$AM_HOME = (Resolve-Path -Path (Join-Path -Path $scriptDir -ChildPath "..\..")).Path
$PIDFILE = Join-Path $AM_HOME "am-agent.pid"

# Returns true if the given Windows service is installed.
function IsServiceInstalled {
    param (
        [string]$ServiceName
    )

    try {
        $service = Get-Service -Name $ServiceName -ErrorAction Stop
        return $true
    } catch {
        return $false
    }
}

function Log-Info {
    param([string]$Message)
    $scriptName = [System.IO.Path]::GetFileName($MyInvocation.ScriptName)
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss.fff zzz"
    Write-Host "[$timestamp] ($scriptName) $Message"
}

# Converts Windows-style paths to Unix-style in a YAML file.
function Convert-WindowsPathsToUnix {
    param(
        [string]$YamlFilePath
    )

    try {
        Log-Info "Converting Windows paths to Unix format in: $YamlFilePath"

        # Read the YAML file
        $content = Get-Content -Path $YamlFilePath -Raw

        # Replace Windows backslashes with forward slashes
        # This regex looks for paths that start with a drive letter and have backslashes
        $content = $content -replace '([A-Za-z]:\\)([^"''\s]+)', '$1$2' -replace '\\', '/'

        # Write the modified content back to the file
        $content | Set-Content -Path $YamlFilePath -NoNewline

        Log-Info "Successfully converted paths in YAML file"
        return $true
    }
    catch {
        Log-Info "Failed to convert paths in YAML file: $_"
        return $false
    }
}

# Converts all Windows-style paths to Unix-style in all YAML files in a directory.
function Convert-AllYamlPaths {
    param(
        [string]$PipelinesDir
    )

    try {
        Log-Info "Converting paths in all YAML files in: $PipelinesDir"

        # Get all YAML files
        $yamlFiles = Get-ChildItem -Path $PipelinesDir -Filter "*.yml"

        foreach ($file in $yamlFiles) {
            Convert-WindowsPathsToUnix -YamlFilePath $file.FullName
        }

        Log-Info "Successfully converted paths in all YAML files"
        return $true
    }
    catch {
        Log-Info "Failed to convert paths in YAML files: $_"
        return $false
    }
}

# Important function to determine the mode in which otel collector should start.
# Determined by install.mode file which is created after install.ps1 is executed.
# Default is process mode
function Get-InstallMode {
    $modeFile = Join-Path $AM_HOME "install.mode"
    if (Test-Path $modeFile) {
        $mode = (Get-Content $modeFile -Raw).Trim()
        if ($mode -eq "service" -or $mode -eq "process") {
            return $mode
        }
    }
    return "process" # Default to process if not set or unknown
}

# Returns true if any otel-collector process is running.
function Is-Otel-Collector-Running-As-A-Process {
    # Checks if the otel-collector process is running using the PID from the PID file
    $allCollectors = Get-Process -Name "otel-collector" -ErrorAction SilentlyContinue
    if ($allCollectors) {
        $allCollectors | ForEach-Object {
            Write-Host "Otel-collector process running with PID $($_.Id)"
        }
        return $true
    } else {
        return $false
    }
}

# Returns true if the otel-collector Windows service is running.
function Is-Otel-Collector-Running-As-A-Service {
    # Checks if the otel-collector Windows service is running
    $svc = Get-Service -Name "am-otel-collector" -ErrorAction SilentlyContinue
    if ($svc -and $svc.Status -eq "Running") {
#        Write-Host "Service 'am-otel-collector' is running."
        return $true
    } else {
#        Write-Host "Service 'am-otel-collector' is NOT running."
        return $false
    }
}

# Returns true if otel-collector is running as a process (by PID file) or as a service.
function Is-Otel-Collector-Running {
    $mode = Get-InstallMode
    if ($mode -eq "process") {
        # OTel collector is supposed to be running as a process
        return Is-Otel-Collector-Running-As-A-Process
    } else {
        # OTel collector is supposed to be running as a service
        return Is-Otel-Collector-Running-As-A-Service
    }
}

function Is-DirectoryWatcher-Running {
    try {
        $dwProcesses = Get-Process java -ErrorAction SilentlyContinue | Where-Object {
            $_.Path -like "*java.exe" -and (Get-CimInstance Win32_Process -Filter "ProcessId=$($_.Id)" -ErrorAction SilentlyContinue).CommandLine -match "com\.mulesoft\.dias\.mule\.agent\.DirectoryWatcher"
        }
        
        if ($null -ne $dwProcesses -and $dwProcesses.Count -gt 0) {
            # Process is found, log information about each process
            foreach ($process in $dwProcesses) {
                Log-Info "DirectoryWatcher is running with PID $($process.Id)"
            }
            return $true
        } else {
            Log-Info "No DirectoryWatcher process is running"
            return $false
        }
    } catch {
        Log-Info "Error checking for DirectoryWatcher: $_"
        return $false
    }
}