<#  
  [PSRoomsigning_CreateResources.ps1]

  *****************************************************************
  *** This is the SETUP script for PSRoomSigning, read the      ***
  *** instructions that came with this script or check website  ***
  *** at https://www.microcloud.nl for information.             ***
  *****************************************************************
#>

#############################################################################################################################
$global:ScriptName           = $MyInvocation.MyCommand.Name                              # current script name
$global:ScriptNameAndPath    = $MyInvocation.MyCommand.Definition                        # put full file and pathname in var.
$global:ScriptPath           = $global:ScriptNameAndPath.Replace($global:ScriptName, "") # current script path
#############################################################################################################################


$global:year=5
$global:defaultpwd="P@ssw0rd"
$global:azlocation="West Europe"
$global:defaultspnname="svc_roomsigning_2021" 


Function Remove-InvalidFileNameChars 
{
  # Source: https://stackoverflow.com/questions/23066783/how-to-strip-illegal-characters-before-trying-to-save-filenames
  param(
    [Parameter(Mandatory=$true,
      Position=0,
      ValueFromPipeline=$true,
      ValueFromPipelineByPropertyName=$true)]
    [String]$Name
  )
  $invalidChars = [IO.Path]::GetInvalidFileNameChars() -join ''
  $re = "[{0}]" -f [RegEx]::Escape($invalidChars)
  return ($Name -replace $re)
}


Function Option1
  {      
     # First ask SPN name
     $SPNName=$global:defaultspnname
     $xSPNName=Read-host "Enter an SPN name? [$SPNName]"
      If ($xSPNName -eq '') 
       {
         $xSPNName=$SPNName
       } else
       {
         $xSPNName=Remove-InvalidFileNameChars ($xSPNName)
       } 
     $SPNname=$xSPNName
     Write-host "Create new SPN name: $SPNname"

     # Second ask PFX password
     $pwd = $global:defaultpwd  # PFX Password
     $xPFXPWD=Read-host "Certificate PFX Password? [$pwd]"
     If ($xPFXPWD -eq '') 
       {
         $pwd=$pwd
       } else
       {
         $pwd=$xPFXPWD
       }        
     
     # Generate info
     $rootfolder=$global:ScriptPath
     $DNSName=($SPNname+".cert.local").ToLower()    
     $AuthFilename=($rootfolder+$DNSName+".txt").ToLower() # Save all info to this file.
     $CertFilename=($rootfolder+$DNSName+".pfx").tolower() # Save Cert with Private key in PFX
     $year=$global:year    
          

     # First login to AzureAD
     Write-host
     Write-Host -ForegroundColor Yellow "Now we need to login to AzureAD, Connect-AzureAD, login in with Global Admin credentials".
     Start-Sleep 3
    
     Connect-AzureAD     
            
     # Create the self signed cert
     $currentDate = Get-Date
     $endDate = $currentDate.AddYears($year)
     $notAfter = $endDate.AddYears(1)

     $thumb = (New-SelfSignedCertificate -CertStoreLocation cert:\currentuser\my -DnsName $DNSName -KeyExportPolicy Exportable -Provider "Microsoft Enhanced RSA and AES Cryptographic Provider" -NotAfter $notAfter).Thumbprint
     $pwd = ConvertTo-SecureString -String $pwd -Force -AsPlainText
     Export-PfxCertificate -cert "cert:\currentuser\my\$thumb" -FilePath $CertFilename -Password $pwd

     # Load the certificate
     $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate($CertFilename, $pwd)
     $keyValue = [System.Convert]::ToBase64String($cert.GetRawCertData())
      
     # Create the Azure Active Directory Application
     $application = New-AzureADApplication -DisplayName $SPNname -IdentifierUris $DNSName #"https://localhost"
     New-AzureADApplicationKeyCredential -ObjectId $application.ObjectId -CustomKeyIdentifier $SPNname -StartDate $currentDate -EndDate $endDate -Type AsymmetricX509Cert -Usage Verify -Value $keyValue
     # Create the Service Principal and connect it to the Application
     $sp=New-AzureADServicePrincipal -AppId $application.AppId
     # /Create Cert
     $AZTenant=Get-AzureADTenantDetail
     Disconnect-AzureAD
     Write-host
   
     # Generic settings
     $logline="SPN Information" 
     $logline | out-file $AuthFilename
     Write-host -ForegroundColor Yellow $logline
     #$logline="TenantID: '$($AZTenant.objectid)'"

     $logline='$TenantID="'+$($AZTenant.objectid)+'"'

     $logline | out-file $AuthFilename -Append
     Write-host -ForegroundColor Yellow $logline
     #$logline="AppID   : '$($application.AppId)'" 

     $logline='$AppID="'+$($application.AppId)+'"'

     $logline | out-file $AuthFilename -Append
     Write-host -ForegroundColor Yellow $logline
     $logline="Thumb   : '$Thumb'" 
     $logline='$Thumb="'+$($Thumb)+'"'

     $logline | out-file $AuthFilename -Append      
     Write-host -ForegroundColor Yellow $logline
     Write-host
     Write-host "Information written to file: $AuthFilename"
     Write-host "Save this info you need it later!"
     Write-host
  } #/Option1

Function Option2
  {
    Write-host
    Write-Host -ForegroundColor Yellow "2: First we need to login to AzureAD and Az, Connect-AzureAD and Connect-AzAccount, login in with Global Admin credentials and Owner permissions on AzureRM".
    Start-Sleep 3
    Connect-AzureAD
    Connect-AzAccount

    # First select the correct Azure Subscription
    Get-AzSubscription | Out-GridView -OutputMode Single -Title "Select the correct subscription:" | Select-AzSubscription

    # Then select the SPN
    $xSelectedApp=Get-AzureADApplication | Out-GridView -OutputMode Single -Title "Select the SPN created earlier!"
    $xSelectedApp.AppId

    # Select the location
    $Azlocation=Get-AzLocation  | Out-GridView -OutputMode Single -Title "Select your preferred location:"   

    $RGroup="RG-PSRoomSigning"
    $xRGroup=Read-host "Enter resource groupname [$RGroup]"
      If ($xRGroup -eq '') 
       {
         $xRGroup=$RGroup
       } else
       {
         $xRGroup=(Remove-InvalidFileNameChars ($xRGroup)).tolower()
       } 

    
    
    $WebAppPrefix="webapp"
    $xWebAppPrefix=Read-host "Enter the Azure WebApp prefix [$WebAppPrefix]"
      If ($xWebAppPrefix -eq '') 
       {
         $xWebAppPrefix=$WebAppPrefix
       } else
       {
         $xWebAppPrefix=(Remove-InvalidFileNameChars ($xWebAppPrefix)).tolower()
       } 
    $webappname=$xWebAppPrefix+((get-date).tostring('ddmmyyhhmmss'))
    Write-host "RGName      : $xRGroup" 
    Write-host "WebAppPrefix: $webappname"
    
    # Create Web App Stuff
    # Create a resource group.
    $location = $($azlocation.location) 
    New-AzResourceGroup -Name $xRGroup -Location $location

    # Create an App Service plan in `Free` tier.
    New-AzAppServicePlan -Name $webappname -Location $location -ResourceGroupName $xRGroup -Tier Free

    # Create a web app.
    $global:re=New-AzWebApp -Name $webappname -Location $location -AppServicePlan $webappname -ResourceGroupName $xRGroup

    # Assign permissions
    $role="Contributor"   

    New-AzRoleAssignment -RoleDefinitionName $role -ResourceName ($webappname) -ResourceGroupName ($xRGroup) -ApplicationId ($xSelectedApp.AppId) -ResourceType ($global:re.Type)

    # Get publishing profile for the web app
    $xml = [xml](Get-AzWebAppPublishingProfile -Name $webappname -ResourceGroupName $xRGroup -OutputFile null)

    # Extract connection information from publishing profile
    $username = $xml.SelectNodes("//publishProfile[@publishMethod=`"FTP`"]/@userName").value
    $password = $xml.SelectNodes("//publishProfile[@publishMethod=`"FTP`"]/@userPWD").value
    $url = $xml.SelectNodes("//publishProfile[@publishMethod=`"FTP`"]/@publishUrl").value

    Write-Host "FTP Url     : $url"
    Write-Host "FTP username: $username"
    Write-Host "FTP password: $password"
    Write-Host
    Write-Host "Save the FTP info for reference. Note you can always find them back in Azure Portal."
    # /Create Web App Stuff
   
    Disconnect-AzureAD
    Disconnect-AzAccount
  }


Write-host -ForegroundColor green "Welcome at PSRoomSigning PSRoomsigning_CreateResources.ps1"
Write-host
Write-host -ForegroundColor green "1 - Create the SPN (You need to give it Calendar.Read API permissions via Azure AD Portal)."
Write-host -ForegroundColor green "2 - Create Azure App Service (Azure WebServer) and give SPN permissions to Azure WebServer"
Write-host
$choice1 = read-host "  Enter the number"
If ($choice1 -eq 1)
  {
    Option1
  } else
  {
    Option2
  }


