# Fonction pour les requetes SQL
Function QuerySQLServer([string]$DBServer, [string]$DBName, [string]$Query) {
    Try {
        $ErrorActionPreference = "Stop"
   
        $resultsDataTable = New-Object System.Data.DataTable

        $cn = new-object System.Data.SqlClient.SqlConnection("Data Source=$DBServer;Integrated Security=SSPI;Initial Catalog=$DBName")
        $cn.open()
 
        $cmd = new-object "System.Data.SqlClient.SqlCommand" ($Query , $cn)
        $reader = $cmd.ExecuteReader()
     
        $resultsDataTable.Load($reader)

        $cn.Close()

        return $resultsDataTable
    }
    Catch {
        write-host $_.Exception.Message
        $_.Exception.Message >> "d:\tmp\error.log"
    }
    Finally {
     $ErrorActionPreference = "Continue"
    }
}

# Fonction pour les requetes dans GLPI
Function QueryGLPI([string]$Titre, [string]$Message, [string]$Categorie) {
    Write-host $Titre
    Write-host $Message
    Write-host $Categorie

    $UtilisateurGLPI = Get-GlpiToolsUsers -UserName helpdesk

    $Ticket = New-GlpiToolsTicket -Name $Titre -Content $Message -Type Request -itilcategories_id $Categorie -Priority Medium -requester_id $UtilisateurGLPI.ID

    Update-GlpiToolsTicket -ticket_id $Ticket.id -requester_id $UtilisateurGLPI.ID -technician_id '12'
}

cls

$ListeException   = $null
$ListeVide        = $null
$FichierException = "D:\tmp\Exception.txt"
$FichierVide      = "D:\tmp\vide.txt"
$percentCompleteA = $null
$percentCompleteB = $null
$CounterA         = $null
$CounterB         = $null
$EtatUtilisateur  = $null

$DateDesactivation = Get-Date -Format "dd/MM/yyyy"
$DateExpiration    = (Get-Date $DateDesactivation).AddDays(-1)
$DateDelete        = (Get-Date $DateDesactivation).AddDays(-30)

$DateTmp           = (Get-Date).AddDays(-1)
$DateCreation      = Get-Date $DateTmp -Format "yyyy-dd-MM"

Start-Transcript -path "D:\tmp\MyTranscript-$DateCreation.txt"

$OuPath = "OU=Utilisateurs,DC=fr,DC=dgs,DC=group"
$ListeUserAD = Get-ADUser -Filter * -SearchBase $OuPath -Properties cn,description,sAMAccountName 

## Desactivation ou Update de compte

Foreach ($UserAD in $ListeUserAD) {
    # Barre de progression
    $percentCompleteA = $(($CounterA / $ListeUserAD.Count) * 100 )

    $ProgressA = @{
        Activity = "Getting folder information for '$($UserAD.Name)'."
        Status = "Processing $CounterA of $($ListeUserAD.Count)"
        PercentComplete = $([math]::Round($percentCompleteA, 2))
    }

    Write-Progress @ProgressA -Id 1

    # recherche inforamtiopn 1 utilisateur
    $InfoUser = Get-ADUser -identity $UserAD.sAMAccountName -properties 'msDS-cloudExtensionAttribute1','msDS-cloudExtensionAttribute2',mail,employeeID,EmployeeNumber,EmployeeType,Title,Initials

    $C              = $UserAD.C
    $City           = $UserAD.City
    $Cn             = $UserAD.Cn
    $Company        = $UserAD.Company
    $department     = $UserAD.Department
    $displayName    = $UserAD.DisplayName
    $EmailAddress   = $UserAD.EmailAddress
    $Enable         = $UserAD.Enabled
    $GivenName      = $UserAD.GivenName
    $Name           = $UserAD.Name
    $Office         = $UserAD.Office
    $Organization   = $UserAD.Organization
    $PostalCode     = $UserAD.PostalCode
    $sn             = $UserAD.Sn
    $Surname        = $UserAD.Surname

    $ExtensionAttribute1 = $InfoUser.'msDS-cloudExtensionAttribute1'
    $ExtensionAttribute2 = $InfoUser.'msDS-cloudExtensionAttribute2'
    $Mail                = $InfoUser.Mail
    $EmployeeID          = $InfoUser.employeeID
    $EmployeeNumber      = $InfoUser.EmployeeNumber
    $EmployeeType        = $InfoUser.EmployeeType
    $Title               = $InfoUser.Title
    $Initials            = $InfoUser.Initials

    # Est-ce qu'il est actif
    If ($Enable -eq "True") {
        # Est-ce qu'il est interne
        If($EmployeeType -eq "Interne") {
            # Est-ce qu'il a un ID
            If ($EmployeeID) {
                # Si l'employeeID est bien présent
                $EtatUtilisateurD = QuerySQLServer "SWDHBBDDP01.fr.dgs.group" "dhb_prd" "SELECT NOM,PRN,NOM_PAT,LIB_EMP,ADR_EML,MTR,NUM_ALC,COD_SEX,FLG_AGT,DAT_SRT FROM [dhb_prd].[dhbref].[TAB_RH_SAL] WHERE MTR = '$EmployeeID' And DAT_SRT IS NOT NULL"
                $EtatUtilisateurU = QuerySQLServer "SWDHBBDDP01.fr.dgs.group" "dhb_prd" "SELECT NOM,PRN,NOM_PAT,LIB_EMP,ADR_EML,MTR,NUM_ALC,COD_SEX,FLG_AGT,DAT_SRT FROM [dhb_prd].[dhbref].[TAB_RH_SAL] WHERE MTR = '$EmployeeID'"
                
                # Desactivation du compte ?
                If ($EtatUtilisateurD) {
                    If ($DateExpiration -gt $EtatUtilisateurD.DAT_SRT) {

                        Get-ADUser -Identity $UserAD.sAMAccountName | Move-ADObject -TargetPath "OU=_A_SUPPRIMER,OU=Utilisateurs,DC=fr,DC=dgs,DC=group"
                        Set-ADAccountExpiration -Identity $UserAD.sAMAccountName -DateTime $dateExpiration
                        Set-ADUser -Identity $Utilisateur -Clear msDS-cloudExtensionAttribute2
                        Set-ADUser -Identity $UserAD.sAMAccountName -Add @{'msDS-cloudExtensionAttribute2' = "$DateExpiration"}
                        Disable-ADAccount -Identity $UserAD.sAMAccountName

                        $TitreA   = "Désactivation du compte Active Directory : $UserAD.sAMAccountName "

                        $MessageA = "Bonjour, `r`n `r`n" `
                        +"Nous venons de désactiver le compte de : $DisplayName `r`n `r`n" `
                        +"Prénom : $GivenName `r`n" `
                        +"Nom : $Surname `r`n" `
                        +"Mail : $Mail `r`n" `
                        +"Matricule : $EmployeeID `r`n" `
                        +"Fonction : $Title `r`n" `
                        +"`r`n" `
                        +"Conformément à la politique entreprise le compte restera en état désactivé pendant 30 jours avant d'être supprimé `r`n" `
                        +"La suppression du compte GMAIL se fait également en automatique."

                        QueryGLPI $TitreA $MessageA "213"
                    }
                }

                # Mise en place de la civilité
                If ($EtatUtilisateurU) {
                    If (($Initials -ne "Mr") -And ($EtatUtilisateurU.COD_SEX -eq "H")) {

                        Set-ADUser -Identity $UserAD.sAMAccountName -Clear Initials
                        Set-ADUser -Identity $UserAD.sAMAccountName -Initials "Mr"

                        Write-Host " - Update civilité - Mr"
                    }
                    ElseIf (($Initials -ne "Mme") -And ($EtatUtilisateurU.COD_SEX -eq "F")) {

                        Set-ADUser -Identity $UserAD.sAMAccountName -Clear Initials
                        Set-ADUser -Identity $UserAD.sAMAccountName -Initials "Mme"

                        Write-Host " - Update civilité - Mme"
                    }
                    Else {
                        # Write-Host " - Pas de modification"
                    }
                }

                # Mise en place du Employee Number
                If ($EmployeeNumber -ne $EtatUtilisateurU.NUM_ALC) {
                    If ($EmployeeID.substring(0, 1) -eq 0 ) {
                        $tmp = ($EtatUtilisateurU.NUM_ALC).Remove(0,1)
                        If (!($EmployeeNumber -eq $tmp)) {
                            Write-host " - 2erreur : "$EtatUtilisateurU.MTR" > $EmployeeID | "$EtatUtilisateurU.NUM_ALC" > $EmployeeNumber"
                        }
                    }
                    Else {
                        Write-host " - erreur : "$EtatUtilisateurU.MTR" > $EmployeeID | "$EtatUtilisateurU.NUM_ALC" > $EmployeeNumber"
                    }
                }
				
				# Controle du status
				If (($ExtensionAttribute1 -eq $null) -Or ($ExtensionAttribute1 -ne $EmployeeType)) {
					Set-ADUser -Identity $UserAD.sAMAccountName -Add @{'msDS-cloudExtensionAttribute1' = $EmployeeType}
				}
            }
            Else {
                # Si l'employé ID n'est pas présent
                $EtatUtilisateurID = QuerySQLServer "SWDHBBDDP01.fr.dgs.group" "dhb_prd" "SELECT NOM,PRN,NOM_PAT,LIB_EMP,ADR_EML,MTR,NUM_ALC,COD_SEX,FLG_AGT,DAT_SRT FROM [dhb_prd].[dhbref].[TAB_RH_SAL] WHERE NOM = '$Surname' And PRN ='$GivenName' And DAT_SRT IS NULL"

                If ($EtatUtilisateurID) {

                    Set-ADUser -Identity $UserAD.sAMAccountName -EmployeeID $EtatUtilisateurID.MTR

                    Write-Host " - Mise en place de employee ID"
                }
            }
        }
        Else {
            # Passage d'un externe en interne
        }
    }
    $EtatUtilisateurD = $null
    $EtatUtilisateurU = $null

    $CounterA++
}

## Suppression des comptes de plus 1 mois

$OuPathDelete = "OU=_A_SUPPRIMER,OU=Utilisateurs,DC=fr,DC=dgs,DC=group"
$ListeUserADDelete = Get-ADUser -Filter * -SearchBase $OuPathDelete -Properties cn,description,sAMAccountName

Foreach ($UserADDelete in $ListeUserADDelete) {
    # Barre de progression
    $percentCompleteB = $(($CounterB / $ListeUserADDelete.Count) * 100 )

    $ProgressB = @{
        Activity = "Getting folder information for '$($UserADDelete.Name)'."
        Status = "Processing $CounterB of $($ListeUserADDelete.Count)"
        PercentComplete = $([math]::Round($percentCompleteB, 2))
    }

    Write-Progress @ProgressB -Id 1

    $InfoUserDelete = Get-ADUser -identity $UserADDelete.sAMAccountName -properties 'msDS-cloudExtensionAttribute2'

    $ExtensionAttributeDelete2 = $InfoUserDelete.'msDS-cloudExtensionAttribute2'

    If ($Enable -eq $False) {
        If ($DateDelete -gt $ExtensionAttributeDelete2) {
            Remove-ADUser -Identity $UserADDelete.sAMAccountName

            $TitreB   = "Suppression du compte Active Directory : $UserAD.sAMAccountName "

            $MessageB = "Bonjour, `r`n `r`n" `
            +"Nous venons de supprimer le compte de : $DisplayName `r`n `r`n" `
            +"Prénom : $GivenName `r`n" `
            +"Nom : $Surname `r`n" `
            +"Mail : $Mail `r`n" `
            +"Matricule : $EmployeeID `r`n" `
            +"Fonction : $Title `r`n" `
            +"`r`n" `
            +"Conformément à la politique entreprise le compte est resté en état désactivé pendant 30 jours `r`n" `
            +"La suppression du compte GMAIL se fait également en automatique."

            QueryGLPI $TitreB $MessageB "213"
        }
    }
    $EtatUtilisateur = $null

    $CounterB++
}

## Creation  compte

$ListeNouveau = QuerySQLServer "SWDHBBDDP01.fr.dgs.group" "dhb_prd" "SELECT NOM,PRN,NOM_PAT,LIB_EMP,ADR_EML,MTR,NUM_ALC,COD_SEX,FLG_AGT,DAT_SRT,NUM_MAG_AGT FROM [dhb_prd].[dhbref].[TAB_RH_SAL] WHERE DTH_CRE >= '$DateCreation' ORDER BY DTH_CRE DESC"
$ListeNouveau | Format-Table
Pause
If ($ListeNouveau) {
    Foreach ($NouveauUtilisateur in $ListeNouveau) {

        $InfoUserNew  = Get-ADUser -Filter * | Where-Object {$_.GivenName -like $NouveauUtilisateur.PRN -and $_.Surname -like $NouveauUtilisateur.NOM}

        If ($InfoUserNew) {
            $InfoUserNewA = Get-ADUser -identity $InfoUserNew.sAMAccountName -properties 'msDS-cloudExtensionAttribute1','msDS-cloudExtensionAttribute2',mail,employeeID,EmployeeNumber,EmployeeType,Title,Initials
        }

        $C              = $InfoUserNew.c
        $City           = $InfoUserNew.City
        $Cn             = $InfoUserNew.cn
        $Company        = $InfoUserNew.company
        $department     = $InfoUserNew.department
        $DisplayName    = $InfoUserNew.displayName
        $EmailAddress   = $InfoUserNew.EmailAddress
        $Enable         = $InfoUserNew.Enabled
        $GivenName      = $InfoUserNew.GivenName
        $Name           = $InfoUserNew.Name
        $Office         = $InfoUserNew.Office
        $Organization   = $InfoUserNew.Organization
        $PostalCode     = $InfoUserNew.PostalCode
        $sn             = $InfoUserNew.sn
        $Surname        = $InfoUserNew.Surname

        $ExtensionAttribute1 = $InfoUserNewA.'msDS-cloudExtensionAttribute1'
        $ExtensionAttribute2 = $InfoUserNewA.'msDS-cloudExtensionAttribute2'
        $Mail                = $InfoUserNewA.Mail
        $EmployeeID          = $InfoUserNewA.employeeID
        $EmployeeNumber      = $InfoUserNewA.EmployeeNumber
        $EmployeeType        = $InfoUserNewA.EmployeeType
        $Title               = $InfoUserNewA.Title
        $Initials            = $InfoUserNewA.Initials

        If ($NouveauUtilisateur.MTR -eq $EmployeeID) {
            Write-host "Existe deja"
        }
        Else {
            Write-Host "A creer"

            $Surnametmp        = ($NouveauUtilisateur.NOM).ToLower()
            $GivenNametmp      = ($NouveauUtilisateur.PRN).ToLower()
            $Titletmp          = ($NouveauUtilisateur.LIB_EMP).ToLower()
            $Initialstmp       = $NouveauUtilisateur.COD_SEX
            $CodeMagtmp        = $NouveauUtilisateur.NUM_MAG_AGT

            $SurnameNew    = (Get-Culture).TextInfo.ToTitleCase($Surnametmp)
            $GivenNameNew  = (Get-Culture).TextInfo.ToTitleCase($GivenNametmp)
            $TitleNew      = (Get-Culture).TextInfo.ToTitleCase($Titletmp)
            $EmployeeIDNew = $NouveauUtilisateur.MTR

            If ($NouveauUtilisateur.NOM_PAT) {
                $SurnamePattmp     = ($NouveauUtilisateur.NOM_PAT).ToLower()
                $SurnamePatNew = (Get-Culture).TextInfo.ToTitleCase($SurnamePattmp)
            }

            $NameNew              = $GivenNameNew+" "+$SurnameNew
            $DisplayNameNew       = $GivenNameNew+" "+$SurnameNew+" "+$SurnamePatNew
            $SamAccountNameNew    = (("$GivenNameNew.$SurnameNew").Replace(' ','').Replace('é','e').Replace('è','e').Replace('ç','c').Replace('ï','i').Replace('î','i').Replace('ë','e').Replace('ö','o').Replace('ô','o')).ToLower()
            $UserPrincipalNameNew = (("$GivenNameNew.$SurnameNew@fr.dgs.group").Replace(' ','').Replace('é','e').Replace('è','e').Replace('ç','c').Replace('ï','i').Replace('î','i').Replace('ë','e').Replace('ö','o').Replace('ô','o')).ToLower()
            $MailNew              = (("$GivenNameNew.$SurnameNew@saint-maclou.com").Replace(' ','').Replace('é','e').Replace('è','e').Replace('ç','c').Replace('ï','i').Replace('î','i').Replace('ë','e').Replace('ö','o').Replace('ô','o')).ToLower()
            $Password             = ([System.Guid]::NewGuid()).ToString()


            If ($SamAccountNameNew.Length -gt 20) {
                $tmp = ($SamAccountNameNew).substring(0, 20)
                $SamAccountNameNew = $tmp
            }

            Write-host $NameNew
            Write-host $DisplayNameNew
            Write-host $SamAccountNameNew
            Write-host $UserPrincipalNameNew
            Write-host $MailNew
            Write-host $Password
            Write-host $EmployeeIDNew
            Write-host $TitleNew

            New-ADUser -Name "$NameNew" -DisplayName "$DisplayNameNew" -GivenName "$GivenNameNew" -Surname "$SurnameNew" -SamAccountName "$SamAccountNameNew" -UserPrincipalName "$UserPrincipalNameNew" -Path "OU=_ARRIVER,OU=Utilisateurs,DC=fr,DC=dgs,DC=group" -AccountPassword (ConvertTo-SecureString "$Password" -AsPlainText -force) -Enabled $true -EmailAddress $MailNew
            
            sleep 10

            Set-ADUser -Identity $SamAccountNameNew  -replace  @{c="FR";co="France";countrycode=250}
            Set-ADUser -Identity $SamAccountNameNew -Add @{'msDS-cloudExtensionAttribute1' = "Interne"}
            Set-ADUser -Identity $SamAccountNameNew -Add @{'EmployeeType' = "Interne"}
            Set-ADUser -Identity $SamAccountNameNew -Add @{'EmployeeID' = "$EmployeeIDNew"}
            Set-ADUser -Identity $SamAccountNameNew -Title "$TitleNew"
            Set-ADUser -Identity $SamAccountNameNew -Description "A remplir par le Helpdesk"
            Set-ADUser -Identity $SamAccountNameNew -City "A remplir par le Helpdesk"

            If ($Initialstmp -eq "H") {
                Set-ADUser -Identity $SamAccountNameNew -Initials "Mr"
                Write-Host "Update civilite - Mr"
            }
            ElseIf ($Initialstmp -eq "F") {
                Set-ADUser -Identity $SamAccountNameNew -Initials "Mme"
                Write-Host "Update civilite - Mme"
            }
            Else {

            }

            $TitreC   = "Creation du compte de : $DisplayNameNew "

            $MessageC = "Bonjour, `r`n `r`n" `
            +"la creation de compte automatique a cree le compte de : $DisplayNameNew `r`n `r`n" `
            +"Prenom : $GivenNameNew `r`n" `
            +"Nom : $SurnameNew `r`n" `
            +"Mail : $MailNew `r`n" `
            +"Password temporaire : $Password `r`n" `
            +"Matricule : $EmployeeIDNew `r`n" `
            +"Fonction : $TitleNew `r`n"

            QueryGLPI $TitreC $MessageC "104"

            $C                   = $Null
            $City                = $Null
            $Cn                  = $Null
            $Company             = $Null
            $department          = $Null
            $DisplayName         = $Null
            $EmailAddress        = $Null
            $Enable              = $Null
            $GivenName           = $Null
            $Name                = $Null
            $Office              = $Null
            $Organization        = $Null
            $PostalCode          = $Null
            $sn                  = $Null
            $Surname             = $Null
            $ExtensionAttribute1 = $Null
            $ExtensionAttribute2 = $Null
            $Mail                = $Null
            $EmployeeID          = $Null
            $EmployeeNumber      = $Null
            $EmployeeType        = $Null
            $Title               = $Null
            $Initials            = $Null
            $Surnametmp          = $Null
            $GivenNametmp        = $Null
            $Titletmp            = $Null
            $Initialstmp         = $Null
            $CodeMagtmp          = $Null
            $SurnameNew          = $Null
            $SurnamePatNew       = $Null
            $GivenNameNew        = $Null
            $TitleNew            = $Null
            $EmployeeIDNew       = $Null
        }
    }
}

Stop-Transcript
