# Delete and stop the service if it already exists.
if (Get-Service auditbeat -ErrorAction SilentlyContinue) {
  Stop-Service auditbeat
  (Get-Service auditbeat).WaitForStatus('Stopped')
  Start-Sleep -s 1
  sc.exe delete auditbeat
}

$workdir = Split-Path $MyInvocation.MyCommand.Path

# Create the new service.
New-Service -name auditbeat `
  -displayName Auditbeat `
  -binaryPathName "`"$workdir\auditbeat.exe`" --environment=windows_service -c `"$workdir\auditbeat.yml`" --path.home `"$workdir`" --path.data `"$env:PROGRAMDATA\auditbeat`" --path.logs `"$env:PROGRAMDATA\auditbeat\logs`" -E keystore.path=`"$workdir\data\auditbeat.keystore`" -E logging.files.redirect_stderr=true"

# Attempt to set the service to delayed start using sc config.
Try {
  Start-Process -FilePath sc.exe -ArgumentList 'config auditbeat start= delayed-auto'
}
Catch { Write-Host -f red "An error occurred setting the service to delayed start." }
