#This script takes a file that contanis relative paths, replace them with given pathes or with default values - can see it in the help.
#After we change the paths to be in good formating e.g. C:\Program Files\Mellanox\....., we can start to check each file if it have driver version.

$script         = $myinvocation.InvocationName
$version        = ""
$filePath       = ""
$filenotFound	= "File not exist in this location"
$exitDetect     = $FALSE
$SystemFolder   = "Windows\System32"
$System64Folder = "Windows\SysWOW64"
$targetdir      = "C:\"
$installDir     = "C:\Program Files\Mellanox\MLNX_VPI"
$badCounter = 0
$goodCounter = 0

$invocation = (Get-Variable MyInvocation).Value
$directorypath = Split-Path $invocation.MyCommand.Path


$outputFile     = "\outputFile.txt"

function mHelp() {
	Write-Host
	Write-Host Usage: $script" -v <driver version>  -f <files path to check> -s <systemFolder> -a <System64Folder> -t <targetDir> -i <installDir> -o <output file> -e" -foregroundcolor cyan
	Write-Host
	Write-Host "-e : flag that will exit when the first wrong file detect" -foregroundcolor cyan
	Write-Host Example 1: $script' -v "4.40.13792" -f "C:\driver_execute\driverFiles.txt" -s "Windows\System32" -a "Windows\SysWOW64" -t "c:\" -i "C:\Program Files\Mellanox\MLNX_VPI" -o "\outputFile.txt"' -foregroundcolor cyan
	Write-Host Example 2: $script' --version "4.4.13607" --filePath "C:\driver_execute\driverFiles.txt -e"' -foregroundcolor cyan
	Write-Host
	Write-Host "default params are:
			   -e value is $exitDetect
			   -s value is $SystemFolder
			   -a value is $System64Folder
			   -t value is $targetdir
			   -i value is $installDir
			   -o value is $($directorypath + $outputFile)" -foregroundcolor cyan
	Write-Host --------------------------------------------------- -foregroundcolor cyan
}

#Parse the input from the user
for ( $i = 0; $i -lt $args.count; $i++ ) {
	switch ($args[$i]) {
		{($_ -eq "-h") -or ($_ -eq "--help")} { 
			mHelp
			exit 1; 
		} 
		{($_ -eq "-v") -or ($_ -eq "--version")} { 
			$i++
			$version = $args[$i]
		}
		{($_ -eq "-f") -or ($_ -eq "--filePath")} {
			$i++
			$filePath = $args[$i]
		} 
		{($_ -eq "-e") -or ($_ -eq "--exitDetect")} {
			$i++
			$exitDetect = $TRUE
		}
		{($_ -eq "-s") -or ($_ -eq "--systemFolder")} {
			$i++
			$SystemFolder = $args[$i]
		} 
		{($_ -eq "-a") -or ($_ -eq "--System64Folder")} {
			$i++
			$System64Folder = $args[$i]
		} 
		{($_ -eq "-t") -or ($_ -eq "--targetDir")} {
			$i++
			$targetdir = $args[$i]
		} 
		{($_ -eq "-i") -or ($_ -eq "--installDir")} {
			$i++
			$installDir = $args[$i]
		}
		{($_ -eq "-o") -or ($_ -eq "--outputFile")} {
			$i++
			$outputFile = $args[$i]
		} 

		default { 
            mHelp
			exit 1
		}
	}
}

#If the input from the user is less then 3 (file, version, tested file) - the script will exit
if ($args.count -lt 3){
	mHelp
	exit 1
}

#creating the output file
$outputFilePath = $($directorypath + $outputFile)

#getting the content from the tested file
$filelist = Get-ChildItem $filePath

#replace and rewite the new and correct path
foreach ($file in $filelist){
    $new = (Get-Content $file.fullname) -replace "INSTALLDIR", $installDir
    Set-Content $file.fullname $new
	
	$new = (Get-Content $file.fullname) -replace "TARGETDIR", $targetdir
    Set-Content $file.fullname $new
	
	$new = (Get-Content $file.fullname) -replace "System64Folder", $System64Folder
    Set-Content $file.fullname $new

	$new = (Get-Content $file.fullname) -replace "SystemFolder", $SystemFolder
    Set-Content $file.fullname $new
}

#open Stream writer - it the best way to write into a file.
$stream = [System.IO.StreamWriter] $outputFilePath

#getting the content from the tested file after we fixed the paths.
$data = Get-Content $filePath

foreach ($line in $data){
	#checking if the file exist if not, we will write it into the output file and to the screen
	if (Test-Path($line)){
		if (($line.split(".").count) -gt 1) {
			#checking if we are in inf file, so we need to read the version from the file.
			if ($line.Split(".")[-1] -eq "inf") {
				$infData = Get-Content $line
				foreach ($infLine in $infData) {
					if ($infLine.StartsWith("DriverVer")) {
							$fileVersion  = $infLine.Split(",")[-1]
							break
						}
				}
			#getting the file version
			} else {
				$property = Get-ItemProperty -Path ($line)
				$fileVersion = $property.VersionInfo.FileVersion
			}
			#good version - like what we get from the user
			if ($fileVersion -eq $version) {
				Write-host("{0,-85} OK!" -f $line) -foregroundcolor green
				$stream.WriteLine("OK! " + $line)
				$goodCounter++
			} else {
				#Not good - mismatch version
				if ($fileVersion -eq $none){
					$fileVersion = "Version not found"
				}
				Write-host("{0,-85} {1, -15} {2, -15} - Error! " -f $line, $fileVersion, $version ) -foregroundcolor Red -backgroundcolor Yellow
				$stream.WriteLine("Error! " + $line + " " + $fileVersion + "  " + $version)
				$badCounter++
			
				#exit if the -e falg is on
				if ($exitDetect)
				{
					exit 1
				}
			}
		}
	}else {
		#File not exist
		Write-host("{0,-85} {1, -15} - Error! " -f $line, $filenotFound) -foregroundcolor Red -backgroundcolor Yellow
		$stream.WriteLine("Error! " + $line + " " + $filenotFound)
	}
}

#Print some statistics numbers
$color =  'Green'
if (($badCounter -gt 0) -or ($goodCounter -gt 0)){
	$color = 'Red'
}

#printing some statistics to the screen
Write-Host 
Write-Host "***********************************************************************************************"
Write-Host "Found " $data.count "files in the file" $filePath
Write-Host "Found " $badCounter "files that we get mismatch driver version " -foregroundcolor $color
Write-Host "Found " $goodCounter "files that got same driver version" -foregroundcolor $color
Write-Host "Total files that checked  " ($goodCounter + $badCounter) -foregroundcolor $color
Write-Host "***********************************************************************************************"


#printing some statistics to the output file
$stream.WriteLine("***********************************************************************************************")
$stream.WriteLine("Found "+ $data.count + " files in the file "  + $filePath)
$stream.WriteLine("Found " + $badCounter + " files that we get mismatch driver version")
$stream.WriteLine("Found " + $goodCounter + " files that got same driver version")
$stream.WriteLine("Total files that checked  "  + ($goodCounter + $badCounter))
$stream.WriteLine("***********************************************************************************************")

#closing the Stream writer
$stream.close()

#return code if we have more then 1 failure
if ($badCounter -gt 0){
    exit 1
}
else{
    exit 0
}