PSmac.psm1

$script:ModuleRoot = $PSScriptRoot

function Empty-MacOSTrash {
    # Empty the Trash on macOS per https://superuser.com/questions/1877663/how-can-i-empty-the-trash-from-the-macos-terminal
    osascript -e 'try' -e 'tell application "Finder" to empty' -e 'end try'
}

function Get-MacOSNetworkInfo {
    $NetstatInfo = netstat -in
    $lines = $NetstatInfo -split "`n"

    $data = for ($i = 1; $i -lt $lines.Length; $i++) {
        $line = $lines[$i] -split "\s+"
        $obj = [PSCustomObject]@{
            Name    = $line[0]
            Mtu     = $line[1]
            Network = $line[2]
            Address = $line[3]
            Ipkts   = $line[4]
            Ierrs   = $line[5]
            Opkts   = $line[6]
            Oerrs   = $line[7]
            Coll    = $line[8]
        }
         $obj
    }

    $data
}

function Get-MacOSRoutingInfo {
    $NetstatInfo = netstat -rn | Select-Object -skip 1
    $lines = $NetstatInfo -split "`n"
    $data
    $section = ""

    $data = foreach ($line in $lines) {
        if ($line -match "^(Internet|Internet6):$") {
            $section = $matches[1]
            continue
        }

        if ($line -match "^(Destination\s+Gateway\s+Flags\s+Netif\s+Expire)$") {
            continue
        }

        if ($line -match "^\s*$") {
            continue
        }

        $columns = $line -split "\s+"
        $obj = [PSCustomObject]@{
            Section     = $section
            Destination = $columns[0]
            Gateway     = $columns[1]
            Flags       = $columns[2]
            Netif       = $columns[3]
            Expire      = if ($columns.Length -gt 4) { $columns[4] } else { $null }
        }
        
        $obj
    }

    return $data
}

function Restart-MacOSApp { 
    param(
        [Parameter(Mandatory, Position = 0)]
        [ValidateScript(
            { $_ -in (Get-Process).Name },
            ErrorMessage = 'Please specify the name of a subdirectory in the current directory.'
        )]
        [ArgumentCompleter(
            {
                param($cmd, $param, $wordToComplete)
                # This is the duplicated part of the code in the [ValidateScipt] attribute.
                [array] $validValues = (Get-Process).Name
                $validValues -like "$wordToComplete*"
            }
        )]
        [String]$AppName
    )
        
    Get-Process $AppName | Stop-Process 
    Start-Sleep -Seconds 1 
    open -a "$AppName"
}


function Start-MacOSApp { 
    param(
        [Parameter(Mandatory, Position = 0)]
        [ValidateScript(
            { $_ -in (Get-ChildItem -Path @("/Applications", "~/Applications") -Filter *.app | Select-Object   @{l = "Name"; e = { $_.name.Replace('.app', '') } }).Name },
            ErrorMessage = 'Please specify the name of a subdirectory in the current directory.'
        )]
        [ArgumentCompleter(
            {
                param($cmd, $param, $wordToComplete)
                # This is the duplicated part of the code in the [ValidateScipt] attribute.
                [array] $validValues = (Get-ChildItem -Path @("/Applications", "~/Applications") -Filter *.app | Select-Object   @{l = "Name"; e = { $_.name.Replace('.app', '') } }).Name
                $validValues -like "$wordToComplete*"
            }
        )]
        [String]$AppName
    )
        
    open -a "$AppName"
}

function Stop-MacOSApp { 
    param(
        [Parameter(Mandatory, Position = 0)]
        [ValidateScript(
            { $_ -in (Get-Process).Name },
            ErrorMessage = 'Please specify the name of a subdirectory in the current directory.'
        )]
        [ArgumentCompleter(
            {
                param($cmd, $param, $wordToComplete)
                # This is the duplicated part of the code in the [ValidateScipt] attribute.
                [array] $validValues = (Get-Process).Name
                $validValues -like "$wordToComplete*"
            }
        )]
        [String]$AppName
    )
        
    Get-Process $AppName | Stop-Process 
}

# Commands run on module import go here
# E.g. Argument Completers could be placed here

if (!$IsMacOS) {
    Write-Warning "This module is only supported on macOS. Importing it on other platforms may lead to unexpected behavior or errors."
}
else {
    Write-Verbose "Running on macOS, proceeding with module initialization."

    # Init Brew if it exists.
    if (Get-Item -Path /opt/homebrew/bin/brew -ErrorAction SilentlyContinue) {
        /opt/homebrew/bin/brew shellenv | Invoke-Expression
    }
    
    # Initialize Powershell completions from brew if they exist.
    if ((Get-Command brew -ErrorAction SilentlyContinue) -and (Test-Path ($completions = "$(brew --prefix)/share/pwsh/completions"))) {
        foreach ($f in Get-ChildItem -Path $completions -File) {
            . $f
        }
    }
}




# Module-wide variables go here
# For example if you want to cache some data, have some module-wide config settings, etc. ... those could go here
# Example:
# $script:config = @{ }

Export-ModuleMember -Function 'Empty-MacOSTrash','Get-MacOSNetworkInfo','Get-MacOSRoutingInfo','Restart-MacOSApp','Start-MacOSApp','Stop-MacOSApp'