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

$ErrorActionPreference = "Stop"

If ($SHOW_HELP) {
    Write-Host "DESCRIPTION: Install 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 "-p [URL]    set SOCKS5 proxy server URL"
    Write-Host "            Example: socks5://user:password@socks5-server:1080"
    Write-Host "-s [ID]     set server ID"
    Write-Host ""

    exit 0
}

If (!$SERVER_ID) {
    Write-Host "Server ID must be provided using the -s option"
    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=Convert-Path $pwd
    }
}

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

$AM_HOME="${HOME_DIR}\am"

$Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding $False

function Initialize-ConfigFiles {
    Remove-Item $AM_HOME\config\filebeat.yml -Force -ErrorAction SilentlyContinue
    Set-Content -Value $Utf8NoBomEncoding.GetBytes($SERVER_ID) -Encoding Byte -Path $AM_HOME\config\server.id
}

function Invoke-ConfigureProxyUrl {
    Remove-Item $AM_HOME\config\proxy.url -Force -ErrorAction SilentlyContinue
    if ($PROXY_URL) {
        Set-Content -Value $Utf8NoBomEncoding.GetBytes($PROXY_URL) -Encoding Byte -Path $AM_HOME\config\proxy.url
    }
}

function Invoke-ConfigureAgent {
    Write-Host "Configuring agent..."

    if (Get-Command java -ErrorAction SilentlyContinue) {
        Invoke-Expression "java -jar ${AM_HOME}\lib\agent-configurator.jar ${HOME_DIR}"
    }
    else {
        Write-Host "Error pushing configuration because java is not installed"
        exit 0
    }
}

function Install-ServiceAgent {
    if (Get-Service filebeat -ErrorAction SilentlyContinue) {
        $service = Get-WmiObject -Class Win32_Service -Filter "name='filebeat'"
        $service.StopService()
        Start-Sleep -s 1
        $service.delete()
    }

    $FILEBEAT_DATA="${AM_HOME}\filebeat\data"
    $FILEBEAT_LOGS="${AM_HOME}\filebeat\logs"

    $workdir="${AM_HOME}\filebeat\win10"

    New-Service -name filebeat `
        -displayName filebeat `
        -binaryPathName "`"$workdir\filebeat.exe`" -c `"$AM_HOME\config\filebeat.yml`" -path.home `"$AM_HOME`" -path.data `"$FILEBEAT_DATA`" -path.logs `"$FILEBEAT_LOGS`""
}

Initialize-ConfigFiles
Invoke-ConfigureProxyUrl
Invoke-ConfigureAgent

$REPLY = Read-Host -Prompt "Do you want to use monitoring as a service? [y|n]"

if ($REPLY -eq 'y') {
    Install-ServiceAgent
}
