#!/usr/bin/pwsh
param(
    [Alias('h')][switch]$SHOW_HELP,
    [Alias('m')][string]$HOME_DIR=""
)

$ErrorActionPreference = "Stop"

If ($SHOW_HELP) {
    Write-Host "DESCRIPTION: Uninstall Anypoint Monitoring FileBeat"
    Write-Host "Usage: .\$($MyInvocation.MyCommand) [options]"
    Write-Host ""
    Write-Host "options:"
    Write-Host "-h          show help and exit"
    Write-Host "-m [DIR]    set home directory - defaults to MULE_HOME"
    Write-Host ""

    exit 0
}

if ([string]::IsNullOrEmpty($HOME_DIR) -Or (-Not (Test-Path -Path $HOME_DIR))) {
    if (-Not ([string]::IsNullOrEmpty($Env:MULE_HOME)) -And (Test-Path -Path $Env:MULE_HOME)) {
        $HOME_DIR=$Env:MULE_HOME
    }
    else {
        cd $(split-path -parent $MyInvocation.MyCommand.Definition)
        cd ..\..
        $HOME_DIR=$pwd
    }
}

Write-Host "MULE_HOME is set to ${HOME_DIR}"

$AM_HOME="${HOME_DIR}\am"


function Check-File-Status($filePath)
{
    if ((Test-Path -Path $filePath) -eq $false) {
        return $false
    }

    $oFile = New-Object System.IO.FileInfo $filePath

    try {
        $oStream = $oFile.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None)

        if ($oStream) {
            $oStream.Close()
        }
        $true
    } catch {
        write-host "Cannot delete agent file is locked"
        return $false
    }
}

function Remove-files($path){
    Get-ChildItem -Path $path | ForEach-Object {
        $status = Check-File-Status("$_")
        if($status){
            Remove-Item $_ -Force
        }
    }
}

function Remove-ConfigFiles {
    Remove-Item $AM_HOME\config\filebeat.yml -Force -ErrorAction SilentlyContinue
    Remove-Item $AM_HOME\config\server.id -Force -ErrorAction SilentlyContinue
    Remove-Item $AM_HOME\config\proxy.url -Force -ErrorAction SilentlyContinue
    Remove-Item $AM_HOME\config\certs -Force –recurse -ErrorAction SilentlyContinue
    Remove-Item $AM_HOME\config\prospectors -Force –recurse -ErrorAction SilentlyContinue
}

function Remove-Agent {
    if (Test-Path $HOME_DIR\lib\mule\mule-core-4*) {
        Remove-files("$HOME_DIR\server-plugins\mule-agent-plugin\lib\modules\mule-agent-dias-*.jar")
        Remove-files("$HOME_DIR\server-plugins\mule-agent-plugin\lib\modules\analytics-metrics-collector-*.jar")
    }
    else {
        Remove-files("$HOME_DIR\plugins\mule-agent-plugin\lib\modules\mule-agent-dias-*.jar")
        Remove-files("$HOME_DIR\plugins\mule-agent-plugin\lib\modules\analytics-metrics-collector-*.jar")
    }
}

function Stop-AgentStandalone {
    Invoke-Expression "${AM_HOME}\bin\am.ps1 -m $HOME_DIR -a stop"
}

function Stop-AgentService {
    $service = Get-WmiObject -Class Win32_Service -Filter "name='filebeat'"
    $service.StopService()
    Start-Sleep -s 1
    $service.delete()
}

Remove-ConfigFiles
Remove-Agent

if (Get-Service filebeat -ErrorAction SilentlyContinue) {
    Stop-AgentService
}
else {
    Stop-AgentStandalone
}
