# Need to know where our script is so we can use full path to all our dependent files.
$InvocationPath = Split-Path -Path $MyInvocation.MyCommand.Path -Parent


function Stop-ETWTrace {
param (
    [parameter(Mandatory=$true)][string]$ETLName,
    [parameter(Mandatory=$true)][string]$LogPath
)

    if (-not (Test-Path $LogPath))
    {
        throw "$LogPath not found"
    }

    wpr -stop "$LogPath\$ETLName.etl"
}


function Clear-ETWTrace
{
    if (-not ((wpr -status) -match "not recording")) {
        wpr -cancel
    }
}

function Start-ETWTrace {
param (
    [parameter(Mandatory=$false)][string]$WprpFile,
    [parameter(Mandatory=$true)][string]$ProfileName,
    [parameter(Mandatory=$false)][switch]$VerboseMode,
    [parameter(Mandatory=$false)][switch]$Filemode,
    [parameter(Mandatory=$false)][string]$LogPath
)


    if($LogPath)
    {
        if (Test-Path $LogPath)
        {
            $tmp = $LogPath
        }
        else
        {
            throw "$LogPath not found"
        }
    }
    else
    {
        $tmp = $env:TEMP
    }


    if ($WprpFile)
    {
        if (Test-Path $WprpFile)
        {
            $strWPRP = "$WprpFile!"
        }
        else
        {
            throw "$WprpFile not found"
        }       
    }

    if ($VerboseMode)
    {
        $strLevel = "verbose"
    }
    else
    {
        $strLevel = "light"
    }

    $p = start-process wpr -ArgumentList "-start `"$strWPRP$ProfileName.$strLevel`" $(if($Filemode) {"-filemode"})"  `
            -Wait -NoNewWindow -PassThru  `
            -RedirectStandardError "$tmp\wpr_err.txt"  `
            -RedirectStandardOutput "$tmp\wpr_std.txt"
        
    if ($p.ExitCode -ne 0)
    {
        $err = Get-Content -Path "$tmp\wpr_err.txt"
        throw "$err"
    }

}


Export-ModuleMember -Function Start-ETWTrace
Export-ModuleMember -Function Stop-ETWTrace
Export-ModuleMember -Function Clear-ETWTrace