
# goto script location
cd $PSScriptRoot
#get first file with *.licsn fileending
$LicenseSerialNumberFile = @(gci '*.licsn')[0]
if ($LicenseSerialNumberFile -le $null)
{
    Write-Output "[SUCCESS] License serial number file not found. Please put license serial number file in the same file location than this script."
    Write-Output "[INFO] Script end."
    pause
    exit
}
Write-Output "[INFO] License serial number file: '$LicenseSerialNumberFile'"
#parse file for first line where hostname is equal to current machines hostname and activation is empty 
$SerialNumbers = Import-Csv $LicenseSerialNumberFile -header SerialNumber,LicenseName,Host,UserName,ActivationStatus -Delimiter ';'
$SerialNumberForActivation = ''
$LicenseCounter = 0
$HostAndDomain = "$((Get-WMIObject Win32_ComputerSystem).Name).$((Get-WMIObject Win32_ComputerSystem).Domain)"
foreach($SerialNumberLine in $SerialNumbers)
{
    $sn = $SerialNumberLine.SerialNumber
    Write-Output "[INFO] Serial number for consideration: '$sn'..."
    if( ($SerialNumberLine.Host -eq $HostAndDomain) -and ($SerialNumberLine.ActivationStatus -le ''))
    {
        $SerialNumberForActivation = $SerialNumberLine.SerialNumber
        Write-Output "[SUCCESS] Serial number for activation found! $SerialNumberForActivation"
        break
    }
    else
    {
        $h = $SerialNumberLine.Host
        Write-Output "[INFO] ...not suitable. Activation already performed for host $h"
    }
    $LicenseCounter = $LicenseCounter + 1
    if($LicenseCounter -eq $SerialNumbers.Count)
    {    
        Write-Output "[ERROR] All licenses in '$LicenseSerialNumberFile' have been activated. No available license found in file. Please check the activation status of the licenses if they match the activation status in the file and update file. If activation status matches, contact vendor to buy more licenses!"
        Write-Output "[INFO] Script end."
        pause
        exit
    }
}
#get first file with serial number for activation and .LicUpd fileending
$PathNameForActivationfile = "$PSScriptRoot\$SerialNumberForActivation" + '.LicUpd'
if (-not (Test-Path $PathNameForActivationfile))
{
    Write-Output "[ERROR] License activation/update file $PathNameForActivationfile for serial number $SerialNumberForActivation not found. Please upload license request, download license update file and put license update file in the same file location than this script."
    Write-Output "[INFO] Script end."
    pause
    exit
}
else
{
    Write-Output "[SUCCESS] License activation/update file for serial number $SerialNumberForActivation found!"
}
#license manager automation license activation
$LicenseManagerAutomationProgramName = 'C:\Program Files (x86)\Common Files\COPA-DATA\STARTUP\LicenseManagerAutomation.exe'
$PathNameForConfirmationfile = "$PSScriptRoot\$SerialNumberForActivation.LicConf"
$LicenseRequestCreationArguments = @(
    "--action","ActivateOffline",
    "--FileNameUpdate",$PathNameForActivationfile,
    "--FileNameConfirmation",$PathNameForConfirmationfile,
    "--WriteInIni"
    )
Write-Output "[INFO] Start: $LicenseManagerAutomationProgramName $LicenseRequestCreationArguments"
$output = cmd /c $LicenseManagerAutomationProgramName $LicenseRequestCreationArguments
Write-Output $output
Write-Output "[INFO] Finish: $LicenseManagerAutomationProgramName $LicenseRequestCreationArguments"
if($output.StartsWith("Error"))
{
    Write-Output "[ERROR] An error occured while activation license $SerialNumberForActivation. Please note exact error number and log the output of the script and contact 
support@copadata.com."
    Write-Output "[INFO] Script end."
    pause
    exit
}
#check if confirmation file was created
cd $PSScriptRoot
if (-not (Test-Path -Path $PathNameForConfirmationfile))
{
    Write-Output "[ERROR] License confirmation file $PathNameForConfirmationfile could not be found. Please check script or create license confirmation file with the License Administration Tool/License Manager with GUI. please also check, if license has been activated and update *.licSn file accordingly."
    Write-Output "[INFO] Script end."
    pause
    exit
}
else
{
    Write-Output "[SUCCESS] License $SerialNumberForActivation activated and confirmation file $SerialNumberForActivation.LicConf created."
    #update lic sn file
    Write-Output "[INFO] Start update LicSn file."
    $TempFile = "$PSScriptRoot\temp.licsn"
    Import-Csv $LicenseSerialNumberFile -header SerialNumber,LicenseName,Host,UserName,ActivationStatus -Delimiter ';' | ForEach-Object {
     if(($_.SerialNumber -eq $SerialNumberForActivation) -and ($_.Host -eq $HostAndDomain))
     {
        $_.UserName = $env:username
        $_.ActivationStatus = "True"
     }
     $_
    } | ConvertTo-Csv -NoTypeInformation -Delimiter ';' | %{$_.Replace('"','')} | Out-File $TempFile 
    get-content $TempFile |
        select -Skip 1 |
        set-content "$TempFile-temp"
        move "$TempFile-temp" $TempFile -Force
    Remove-Item -Path $LicenseSerialNumberFile
    Rename-Item -Path $TempFile -NewName $LicenseSerialNumberFile
    Write-Output "[INFO] Stopp update LicSn file."
}
Write-Output "[INFO] Script end."
exit