<#
.SYNOPSIS
    <Overview of script>

.NOTES
    Version        : 1.0
    Author         : Hubert CORNET
    Creation Date  : <Date>
    Purpose/Change : <Initial script development>

.LINK
    https://www.tips-of-mine.fr

.EXEMPLE
    <Example goes here. Repeat this attribute for more than one example>

.DESCRIPTION
    <Brief description of script>

.PARAMETER <Parameter_Name>
    <Brief description of parameter input required. Repeat this attribute if required>

.INPUTS
    <Inputs if any, otherwise state None>

.OUTPUTS
    <Outputs if any, otherwise state None - example: Log file stored in C:\Windows\Temp\<name>.log>
#>

#---------------------------------------------------------[Initialisations]--------------------------------------------------------

[CmdletBinding()]
Param(
    [Parameter(Position=0,Mandatory=$True)]
    [string]$CheminSource,
    [Parameter(Position=1,Mandatory=$True)]
    [string]$Pattern,
    [Parameter(Position=2,Mandatory=$True)]
    [int]$Pourcentage
    )
    

# Définir l'action d'erreur pour continuer silencieusement
$ErrorActionPreference = "SilentlyContinue"

#----------------------------------------------------------[Declarations]----------------------------------------------------------
# Version Script
$sScriptVersion = "1.0"

#Log File Info
$sLogPath = "C:\Tmp"
$sLogName = "Dichotomie.log"
$sLogFile = Join-Path -Path $sLogPath -ChildPath $sLogName

Start-Transcript -Path $sLogFile -NoClobber

$Date         = Get-Date -Format "yyyyMMdd HHmm"
$FolderBackup = $CheminSource+"\Backup - "+$Date
$FolderLotA   = $CheminSource+"\Lot-A"
$FolderLotB   = $CheminSource+"\Lot-B"
$FolderLock   = $CheminSource+"\Fichier Bloquant - "+$Date
$Compteur     = 0

#-----------------------------------------------------------[Functions]------------------------------------------------------------

Function Login-RestApi {
    [cmdletbinding()]
    param(
        [string] $ApiUrl,
        [string] $OpConUser,
        [string] $OpConPassword
        )
     
        Write-Verbose ("Parameters =")
        Write-Verbose ("ApiUrl: " + $ApiUrl)
        Write-Verbose ("OpConUser: " + $OpConUser)
        Write-Verbose ("OpConPassword: (hidden)")
     
        $ApiUrl = $ApiUrl.ToLower().TrimEnd("/").TrimEnd("/api")
    
        Write-Host ("Logging in to OpCon REST API: " + $ApiUrl)
     
        $Global:OpconRESTApiUrl = $ApiUrl
        $Global:OpconRESTApiUser = $OpConUser
        $Global:OpConRESTApiPassword = $OpConPassword
        $token = Get-OpConApiToken -Url $ApiUrl -User $OpConUser -Password $OpConPassword
        $Global:OpconRESTApiToken = $token.id
     
        $Global:OpconRESTApiAuthHeader = Get-OpConApiAuthHeader -Token $token.id
        Write-Host ('Token successfully stored for future calls in session.')
} 

Function Ignore-SelfSignedCerts {
    add-type -TypeDefinition  @"
        using System.Net;
        using System.Security.Cryptography.X509Certificates;
        public class TrustAllCertsPolicy : ICertificatePolicy {
            public bool CheckValidationResult(
                ServicePoint srvPoint, X509Certificate certificate,
                WebRequest request, int certificateProblem) {
                return true;
            }
        }
"@
    [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
}

Function Get-OpConApiToken {
    [cmdletbinding()]
    param(
        [string] $Url,
        [string] $User,
        [string] $Password
        )
    $tokensUri = -join($Url, "/api/tokens")
    Write-Host ("Retrieving authorization token...")
    Write-Host ("Uri: " + $tokensUri)
    Write-Host ("User: " + $User)
    $tokenObject = @{
        user = @{
            loginName = $User
            password = $Password
        }
        tokenType = @{
            type = "User"
        }
    }
    try
    {
        Ignore-SelfSignedCerts
        #$token = Invoke-RestMethod -Method Post -Uri $tokensUri -Body (ConvertTo-Json $tokenObject) -ContentType 'application/json; charset=utf-8' -ErrorVariable $RestException -SkipCertificateCheck
        $token = Invoke-RestMethod -Method Post -Uri $tokensUri -Body (ConvertTo-Json $tokenObject) -ContentType 'application/json; charset=utf-8' -ErrorVariable $RestException 
    }
    catch
    {
       ## $error = ConvertFrom-Json $RestException.ErrorDetails.Message
        ##Write-Host ("Unable to fetch token for user '" + $user + "'")
        ##Write-Host ("Error Code: " + $error.code)
        ##Write-Host ("Message: " + $error.message)
        Write-Host ("StatusCode: " + $_.Exception.Response.StatusCode.value__)
        Write-Host ("StatusDescription: " + $_.Exception.Response.StatusDescription)
        Write-Host ("Message: " + $_[0].message)
        ##$Global:OpConRESTAPIException = $_
        throw
        ##exit $_.Exception.Response.StatusCode.value__
    }
    Write-Host ("Token retrieved successfully, Id: " + $token.id + ", Valid Until: " + $token.validUntil)
    return $token
    }

    Function Get-OpConApiAuthHeader {
        Param(
            [string] $Token
        )
    
        $authHeader = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
        $authHeader.Add("Authorization", ("Token " + $Token))
    
        return $authHeader
    }

#--------------------------------------------------------[Debut Du Script]---------------------------------------------------------

Login-RestApi -ApiUrl $ServerUrl -OpConUser $OpConUser -OpConPassword $clearPassword 

#Nombre de fichier présent dans le répertoire
$ListFile  = Get-ChildItem -Path $CheminSource"\*" -Include "*.$Pattern" | Select Name,FullName
$FileCount =  $ListFile.count

$PourcentageFichier = (($Pourcentage/100)*$FileCount)
$PourcentageFichier = [math]::floor($PourcentageFichier) 

If (!(Test-Path $FolderBackup)) {
    New-Item -Path $FolderBackup -ItemType Directory
    New-Item -Path $FolderLotA -ItemType Directory
    New-Item -Path $FolderLotB -ItemType Directory
    New-Item -Path $FolderLock -ItemType Directory
}

Foreach ($File in $ListFile) {
    Copy-Item $File.FullName -Destination $FolderBackup

    If ($Compteur -le $PourcentageFichier) {
        Move-Item $File.FullName -Destination $FolderLotA
    }
    Else {
        Move-Item $File.FullName -Destination $FolderLotB
    }

    $Compteur = $Compteur + 1
}

#---------------------------------------------------------[Fin Du Script]----------------------------------------------------------

Stop-Transcript