TxdDocker.psm1

if ((!$env:TXD_DOCKER_ROOT) -or (-not (Test-Path $env:TXD_DOCKER_ROOT))) { 
      if($isLinux){
            $env:TXD_DOCKER_ROOT = '/docker/laravel_docker'
      }else{
            $env:TXD_DOCKER_ROOT = '\\wsl.localhost\txd-docker-dev\docker\txd_docker' 
      }
}else{
      write-host "TXD_DOCKER_ROOT initialized externally at $env:TXD_DOCKER_ROOT"
}

$env:TXD_HOST_FOLDER_PATHS="\\wsl.localhost\txd-docker-dev\mnt\wsl\txd_sites;\\wsl$\txd-docker-dev\mnt\wsl\txd_sites"
$env:TXD_WSL_FOLDER_PATHS="\\wsl.localhost\txd-docker-dev\var\www;\\wsl$\txd-docker-dev\var\www"

if ((!$env:TXD_CONTAINER_NAME) -or (-not (Test-Path $env:TXD_CONTAINER_NAME))) { 
      $env:TXD_CONTAINER_NAME = 'txd_dev_tools'
}else{
      write-host "TXD_CONTAINER_NAME initialized externally at $env:TXD_CONTAINER_NAME"
}


function Get-DockerEnv{
      $env = ($env:TXD_DOCKER_ROOT+'\.env')
      $envExists = Test-Path ($env) -PathType Leaf
      if(!$envExists){
            Write-Error ".env file not found!";
      }
      $ini = [PSCustomObject]@{};
      foreach($line in Get-Content $env) {
            $withoutComments = $line.Split("#")
            $parts = $withoutComments[0].Split("=")
            if($parts.Count -gt 1){
                  Add-member -InputObject $ini -NotePropertyName $parts[0] -NotePropertyValue ($parts[1] -replace "\\", "/")
            }
      }
      if(-not (Get-Member -Name 'WEBSITE_DOMAIN' -InputObject $ini)){
            Add-member -InputObject $ini -NotePropertyName "WEBSITE_DOMAIN" -NotePropertyValue "dev.jsmservice.eu"      
      }

      
      return $ini
}

function Read-YesNo{
      param($question,
            [switch]$defaultToYes)
      $sample = " (y/N)"
      if($defaultToYes){
            $sample =" (Y/n)"
      }
      do { $answer = Read-Host ($question+$sample) } 
      until ("y","n","Y","N","" -ccontains $answer)
      if("y","Y" -ccontains $answer){
            return $true
      }
      if($defaultToYes -and ($answer -eq "")){
            return $true
      }
      return $false
  }


function Set-CodeRemoteURLHandler {
      param(
            [switch] $clear
      )
      
      $rootNode = "HKCU:\Software\Classes\txmt"
      
      if($clear){
            Remove-Item -Path $rootNode -Force -Verbose
      }else{
            new-item -Path $rootNode -Value "URL:txmt" -force
            new-itemProperty -Path $rootNode -Name "URL Protocol" -PropertyType String  -force
            new-item -Path "$rootNode\shell" -force
            new-item -Path "$rootNode\shell\open" -force
            new-item -Path "$rootNode\shell\open\command" -Value "pwsh -WindowStyle Hidden -Command `"open-dockerdev '%1' -Link`"" -force 
      }
}

function Set-GitExURLHandler {
      param(
            [switch] $clear
      )
      
      $rootNode = "HKCU:\Software\Classes\gitex"
      
      if($clear){
            Remove-Item -Path $rootNode -Force -Verbose
      }else{
            new-item -Path $rootNode -Value "URL:gitex" -force
            new-itemProperty -Path $rootNode -Name "URL Protocol" -PropertyType String  -force
            new-item -Path "$rootNode\shell" -force
            new-item -Path "$rootNode\shell\open" -force
            new-item -Path "$rootNode\shell\open\command" -Value "pwsh -WindowStyle Hidden -Command `"open-gitex '%1'`"" -force 
      }
}

function Set-CodeRemoteContextMenu {
      param(
            [switch] $clear
      )

      $rootNode = "HKCU:\Software\Classes\Directory\Background\shell\TxdDocker"
      
      New-Item -ItemType Directory -Path C:\txd\assets\ -Force
      Copy-Item "$env:TXD_DOCKER_ROOT\assets\TxdDocker.ico" -Destination "C:\txd\assets\TxdDocker.ico"
      
      if($clear){
            Remove-Item -Path $rootNode -Force -Verbose
      }else{
            new-item -Path $rootNode -Value "Open in TxdDocker" -force
            new-itemProperty -Path $rootNode -Name "Icon" -Value "C:\txd\assets\TxdDocker.ico" -PropertyType String  -force
            
            new-item -Path "$rootNode\command" -Value "pwsh -WindowStyle Hidden -Command `"open-dockerdev '%V' -External`"" -force 
      }
}

function Open-GitEx {
      param(
            $path
      )
      $final = $path -replace "gitex://", ""
      gitex $final
      
}

function Open-DockerDev{
      param(
            $path,
            [switch]$link = $false,
            [switch]$external = $false
      )
      $dockerEnv = Get-DockerEnv
      
      $containerStructure = '{"containerName":"/'+$env:TXD_CONTAINER_NAME+'","cwd":"\\\\wsl.localhost\\txd-docker-dev\\docker\\txd_docker"}'
      $containerName = ((Format-Hex -InputObject $containerStructure).Bytes |ForEach-Object ToString X2) -join ""
      
      if($link){
            $mainUrl = ([uri]::UnescapeDataString($path) -split "file://")[1]
            $path = ($mainUrl -split "&line=")[0] -replace "\\", "/"
            $line = ($mainUrl -split "&line=")[1]
            $url = "vscode://vscode-remote/attached-container+$containerName${path}:${line}"
            $command = "code --open-url -- $url"
            write-host $command
            invoke-expression $command
            return
      }
      
      if($external){
            $validExternalPaths = $env:TXD_HOST_FOLDER_PATHS -split ';'
            $found = $false
            foreach($validPath in $validExternalPaths) {
                  if($path.StartsWith($validPath)){
                        $path = $path.replace($validPath,"") -replace "\\", "/"
                        $found = $true
                        break
                  }
            }
            
            if(!$found){
                  write-host "invalid path: $path"
                  return;
            }
      }

      if(("" -eq ("{0}" -f $path).Trim())){
            $devPath = "/root"
      }else{
            $devPath = (Join-Path $dockerEnv.WEBSITE_LOCAL_PATH $path) -replace "\\", "/"
      }
      
      
      
      $command = "code --folder-uri 'vscode-remote://attached-container+$containerName$devPath'"
      
      #$command = "wsl -d txd-docker-dev code"
      write-host $command
      invoke-expression $command
} 

function Open-DockerDevShell{
      param(
            $path
      )
      $dockerEnv = Get-DockerEnv
      $devPath = (Join-Path $dockerEnv.WEBSITE_LOCAL_PATH $path) -replace "\\", "/"
      $shell = $dockerEnv.DEFAULT_SHELL
      invoke-expression "docker exec -it -w $devPath $env:TXD_CONTAINER_NAME $shell"
} 


$dockerdev_block = {
      param($commandName,$parameterName, $wordToComplete)
      
      $subfolder = ""
      $matchingWord = $wordToComplete
      if($wordToComplete.Length -eq 0){
            $subfolder = ""
      }else{
            if($wordToComplete -match '(.*)\/(.*)'){
                  
                  $subfolder = $Matches.1
                  $matchingWord = $Matches.2
            }
      }
      
      $validExternalPaths = $env:TXD_HOST_FOLDER_PATHS -split ';'
      $validPath = $validExternalPaths[0]
      
      $fullpath = (join-path $validPath $subfolder)
      
      $list = Get-ChildItem -directory $fullpath | ForEach-Object {$_.Name}
      if($matchingWord.Length -gt 0 ){
            $list = $list | Select-String -Pattern $matchingWord
      }
      
      $list | Sort-Object | ForEach-Object {
            
            if($subfolder.Length -eq 0){
                  $fullParam = (Join-path $_ "/")  -replace "\\", "/"
            }else{
                  $fullParam = (Join-path  $subfolder $_ "/")  -replace "\\", "/"
            }
            New-Object -Type System.Management.Automation.CompletionResult -ArgumentList $fullParam,
              $_,
              "ParameterValue",
              $fullParam
        }
}

Register-ArgumentCompleter -CommandName Open-DockerDev -ParameterName "path" -ScriptBlock $dockerdev_block
Register-ArgumentCompleter -CommandName Open-DockerDevShell -ParameterName "path" -ScriptBlock $dockerdev_block


Export-ModuleMember -Function Get-DockerEnv, Open-DockerDev, Open-DockerDevShell,Open-GitEx, Set-GitExURLHandler, Set-CodeRemoteURLHandler, Set-CodeRemoteContextMenu -Alias *