TxdDocker.psm1

if (-not (Test-Path env:TXD_DOCKER_ROOT)) { $env:TXD_DOCKER_ROOT = 'C:\docker\laravel_docker' }

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 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) {
            $parts = $line.Split("=")
            if($parts.Count -gt 1){
                  Add-member -InputObject $ini -NotePropertyName $parts[0] -NotePropertyValue ($parts[1] -replace "\\", "/")
            }
      }
      Add-member -InputObject $ini -NotePropertyName "vhostsPath" -NotePropertyValue (Join-Path $env:TXD_DOCKER_ROOT "nginx/vhosts")
      Add-member -InputObject $ini -NotePropertyName "templatePath" -NotePropertyValue (Join-Path $env:TXD_DOCKER_ROOT "nginx")
      Add-member -InputObject $ini -NotePropertyName "composeFile" -NotePropertyValue (Join-Path $env:TXD_DOCKER_ROOT "docker-compose.yml")
      return $ini
}

function Get-DockerWebsiteName{
      param([switch]$noDefault)
      $dockerEnv = Get-DockerEnv
      $list = Join-Path $dockerEnv.vhostsPath "*"
            | Get-ChildItem -Include *.conf
            | Foreach-object { ([regex]::matches( $_,"[\w\.\-_]+(?=.conf)")).Value}
      if($noDefault){
            $list = $list | Where-Object { $_ –ne "default" }
      }
      $list
}

function Update-DockerWebsiteList{
      $dockerEnv = Get-DockerEnv
      Join-Path $dockerEnv.vhostsPath "*"
            | Get-ChildItem -Include *.conf
            | Foreach-object { ([regex]::matches((Get-Content $_),"(?<=server_name )[\w\.\-_]+")).Value}
            | Sort-Object
            | Set-Content (Join-Path $dockerEnv.WEBSITE_LOCAL_PATH "site_list.txt")
      Get-Content (Join-Path $dockerEnv.WEBSITE_LOCAL_PATH "site_list.txt")
}
function Restart-DockerWebserver{
      $dockerEnv = Get-DockerEnv
      docker-compose -f $dockerEnv.composeFile restart
}
function Remove-DockerWebsite{
      param($name)
      $dockerEnv = Get-DockerEnv
      $fullpath = (Join-Path $dockerEnv.vhostsPath "$name.conf")
      if($name -eq "default"){
            Write-Error "Attenzione! non puoi rimuovere il sito di default"
            return
      }
      
      if(Test-Path $fullpath -PathType Leaf){
            Remove-Item $fullpath
      }else{
            Write-Warning "$fullpath non trovato"
      }
      Update-DockerWebsiteList | Out-Null
}


function Add-DockerWebsite{
      param($folderPath=(get-location).Path)
      $dockerEnv = Get-DockerEnv
      $hostname = $dockerEnv.PC_NAME
      $laravelSite = Read-YesNo "Il sito è un progetto Laravel?" -defaultToYes
      $folderPath = $folderPath -replace "\\", "/"
      $oldFolderPath = $folderPath
      $folderPath = $folderPath -replace $dockerEnv.WEBSITE_LOCAL_PATH,"" -replace "^/",""
      $confirmFolder = $false
      if($folderPath -ne $oldFolderPath){
            $fullPath = Join-Path $dockerEnv.WEBSITE_LOCAL_PATH $folderPath
            $confirmFolder = Read-YesNo "Vuoi registrare il percorso corrente ($fullPath)?" -defaultToYes
      }
      if(!$confirmFolder){
            do {
                  $folderPath = Read-Host ("Inserisci il percorso 'relativo' del sito da aggiungere, a partire dalla root riportata sopra (per i sistemi laravel e' la cartella principale SOPRA a public, per gli altri il punto di acceso diretto)`n"+$dockerEnv.WEBSITE_LOCAL_PATH) #`
            }
            until (Test-Path (Join-Path $dockerEnv.WEBSITE_LOCAL_PATH $folderPath) -PathType Container)
      }
      do {
            Write-Output "seleziona la versione di php:"
            Write-Output "1) php-7.1"
            Write-Output "2) php-7.3"
            $php = Read-Host ("selezione")
      }
      until ("1","2" -ccontains $php)
      $defaultPrefix = $folderPath -replace "/","."
      Write-Output "Inserisci il prefisso del sito (che andra' a comporre l'url: prefisso.$hostname.dev.jsmservice.eu)"
      $prefix = Read-Host "(default $defaultPrefix)"
      if ($prefix.Length -eq 0){
            $prefix = $defaultPrefix
      }
      if($prefix -eq "default"){
            Write-Error "Attenzione! non puoi sovrascrivere il sito di default"
            Write-Output "azione annullata"
            return
      }
      if((Get-DockerWebsiteName).Contains($prefix)){
            Write-Warning "Il file $prefix.conf esiste già"
            if(!(Read-YesNo "Sovrascriverlo?")){
                  Write-Output "azione annullata"
                  return
            }
      }

      $addToHosts = Read-YesNo "Vuoi aggiungere il puntamento del sito al file hosts?"

      $fullUrl = "$prefix.$hostname.dev.jsmservice.eu"
      Write-Output "Configuring $fullUrl"
      Write-Output "Generating .conf file"

      if($php -eq 1){
            $template = Join-Path $dockerEnv.templatePath "template-php71"
      }else{
            $template = Join-Path $dockerEnv.templatePath "template-php73"
      }
      if(!$laravelSite){
            $template = $template+"-base"
      }
      $template = $template+".conf"
      $relativePath = "/var/www/$folderPath"
      if($laravelSite){
            $relativePath = $relativePath+"/public"
      }

      if($addToHosts){
            "127.0.0.1 $fullUrl" >> C:/Windows/System32/drivers/etc/hosts
      }

      $outTemplate = (Get-Content $template) -replace "##SITE_NAME##",$fullUrl -replace "##SITE_PATH##",$relativePath

      $outTemplate > (Join-Path $dockerEnv.vhostsPath "$prefix.conf")

      Write-Output "created file " (Join-Path $dockerEnv.vhostsPath "$prefix.conf")
      Update-DockerWebsiteList | Out-Null
      Write-Output "Site List refreshed"
      Write-Output "Restarting Docker"
      docker-compose -f $dockerEnv.composeFile restart nginx
      Write-Output "Done!"
}

$rm_block = {
      param($commandName, $wordToComplete)
      $list = Get-DockerWebsiteName -noDefault
      if($commandName.Length -gt 0 ){
            $list = $list | Select-String -Pattern $commandName
      }
      $list | Sort-Object
  }
Register-ArgumentCompleter -Native -CommandName Remove-DockerWebsite -ScriptBlock $rm_block
Export-ModuleMember -Function Get-DockerEnv, Add-DockerWebsite, Update-DockerWebsiteList, Restart-DockerWebserver, Remove-DockerWebsite -Alias *