# Copyright (C) 2015-present Lenovo. All right reserved.
# Confidential and Restricted

trap {"An error trapped..."}

# ::***********************************************************************************************
# :: Definition-1: Check bitness of OS, process, guid of old version
# ::***********************************************************************************************
$OS_BITNESS=32
if([Environment]::Is64BitOperatingSystem -eq $True) {
$OS_BITNESS=64
}

$PS_BITNESS=32
if([Environment]::Is64BitProcess -eq $True) {
$PS_BITNESS=64
}

$arch="x86"
if ($OS_BITNESS -eq 64) {
$arch="x64"
}

$PRODCODE64="{CBEDEC16-C4F5-4255-99E4-5884EFEDD1BC}"
$PRODCODE32="{01DBFF2E-73FD-4CC3-98CE-B39260D80D8C}"
$PRODCODE64_OLD="{B8D3ED8D-A295-44C2-8AE1-56823D44AD1F}"
$PRODCODE32_OLD="{840DE7EE-4816-4402-BEE4-80517B3233A3}"


# ::***********************************************************************************************
# :: Definition-2: common variables and functions
# ::***********************************************************************************************
$PackageName = "LenovoBatteryGaugeAddin"
$PathPackageDirDest = "$PSScriptRoot"
$PathPackageDirSource = "$PSScriptRoot"
$PathShortCutDir = "$env:ProgramData\Lenovo\Vantage\AddinData\$PackageName"
$PathImcOldBGPackage = "$env:ProgramData\Lenovo\ImController\Plugins\LenovoBatteryGaugePackage"


# ::***********************************************************************************************
# :: Definition: Write-Log
$LogFileName = ("$PackageName" + ".Install." + (Get-Date -Format "-yyyy_MM_dd-HH-mm-ss") + ".txt")
$PathLogFile = "$env:ProgramData\Lenovo\Vantage\Logs\$PackageName\$LogFileName"

[bool]$EnableLogging = $false
try { $EnableLogging = ((Get-ItemPropertyValue -Path "HKLM:\SOFTWARE\WOW6432Node\Lenovo\Vantageservice\FileLogger" -Name "LenovoVantageService").ToLower() -eq "trace" ) } catch{}

if($EnableLogging -and ( -not(Test-Path $PathLogFile))) {
	New-Item -Path (Split-Path $PathLogFile) -Name (Split-Path $PathLogFile -leaf) -ItemType File -force
}

$PSDefaultParameterValues["Write-Log:pathToLogFile"]=$PathLogFile
$PSDefaultParameterValues["Write-Log:enableLogging"]=$EnableLogging

Function Write-Log
{
    [CmdletBinding()]
    param(
		[Parameter(
			Mandatory=$false,
			Position=1,
			ValueFromPipeline=$true
		)]
		[PSObject[]]$inputObject,
        [string]$pathToLogFile=".\" + [System.IO.Path]::GetFileName($MyInvocation.ScriptName) + ".log",
		[bool]$enableLogging=$true
    )

    $obj=$null
    if($input -ne $null)
    {
        $obj=$input
    }
    else
    {
        $obj=$inputObject
    }

    Out-Host -InputObject $obj
    if($enableLogging)
    {
		$timeStamp = $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss  ')
		$objTS = $timeStamp + $obj

	  	Out-File -InputObject $objTS -FilePath $pathToLogFile -Encoding unicode -Append -Width 200
    }
}

# get BG version
$BgDllVersionInfo = "1.0.0.0"
if(Test-Path "$PathPackageDirDest\$arch"){
	$BgDllVersionInfo = (Get-Item "$PathPackageDirDest\$arch\LenovoBatteryGaugePackage.dll").VersionInfo.FileVersion
}


Function PrintDestPackageDetails
{
	if($EnableLogging)
	{
		if(Test-Path "$PathPackageDirDest\$arch")
		{
			Write-Log "Current BG dll version: [$BgDllVersionInfo]"
			Get-ChildItem -Path "$PathPackageDirDest" -Recurse | Select-Object Name, LastWriteTime, Length | Out-File  $PathLogFile -Encoding unicode -Append
		}
		else
		{
			Write-Log "The dest package dir does not exist($PathPackageDirDest\$arch)"
		}
	}
}


# Set Registry flag
Function SetScriptFlagToReg
{
#	param([string]$nameStr)
#	
#	$BgVersionReg = "HKLM:\SOFTWARE\Lenovo\QuickSetting\$BgDllVersionInfo"
#	if( -not(Test-Path -Path "$BgVersionReg") )
#	{
#		 New-Item -Type Directory "HKLM:\SOFTWARE\Lenovo\QuickSetting"
#		 New-Item -Type Directory "HKLM:\SOFTWARE\Lenovo\QuickSetting\$BgDllVersionInfo"
#	}
#
#	$dateTimeStamp = (Get-Date -Format "yyyy_MM_dd-HH-mm-ss")
#
#	New-ItemProperty -Path "$BgVersionReg" -Name "$nameStr" -Value "$dateTimeStamp" -PropertyType String -Force
}

Function UninstallMsi($prodCode)
{
	$uninstallString = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$prodCode" -Name "UninstallString" -ErrorAction SilentlyContinue).UninstallString
	if (($UninstallString -ne $null) -and ($uninstallString.Length -ne 0)) {
		Write-Log "start uninstall msi package for PRODCODE $prodCode"
		$MSIEXECPATH = "$env:SystemRoot\System32\MsiExec.exe"
		Write-Log "Start-Process -NoNewWindow -Wait -FilePath $MSIEXECPATH `"/X$prodCode /quiet /noreboot`""
		Start-Process -NoNewWindow -Wait -FilePath $MSIEXECPATH "/X$prodCode /quiet /noreboot" *>&1 | Write-Log
	}
	else
	{
		Write-Log "cannot find uninstall entry for program PRODCODE $prodCode"
	}
}

Function GetCurrentActiveUserSID
{
	$activeUser = Get-WmiObject Win32_ComputerSystem -ComputerName $env:computername -EA stop | Select UserName -Unique|%{"{0}" -f $_.UserName.ToString().Split('\')[1]}
	$objUser = New-Object System.Security.Principal.NTAccount("$activeUser")
	$strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
	$strSID.Value
}

Function CheckCVLibrarySignature($moduleFullPathName)
{
	$ASValid = $False
	$ASCheck  =Get-AuthenticodeSignature $moduleFullPathName
	if($ASCheck -ne $null)
	{
		if ( ($ASCheck.Status.ToString()).ToLower() -eq "valid" )
		{
			$ASValid = $True
		}
	}

	if($ASValid -eq $False)
	{
		Write-Log "CV lib signature invalid! So exit installation!!!"
		SetScriptFlagToReg "ScriptAbort_NotSign"
		Exit
	}
}


# ::***********************************************************************************************
# :: Definition: BatteryGaugeIconControl
$applicationName = "$env:SystemRoot\system32\rundll32.exe"
$ShowBg = "ShowBatteryGauge"
$HideBg = "HideBatteryGauge"
$UnloadBg = "UnloadBatteryGaugeFromExplorer"
$InstallFileName = "Install.ps1"
$UninstallFileName = "Uninstall.ps1"

# Check file signature validation

CheckCVLibrarySignature("$PSScriptRoot\Lenovo.CertificateValidation.dll")

Import-Module "$PSScriptRoot\Lenovo.CertificateValidation.dll"

Function IsTrustedAssemblyFile($fullFileName)
{
	 $validRet = [Lenovo.CertificateValidation.FileValidator]::GetTrustStatus($fullFileName)

	 Write-Log "Check file signature result: [$validRet], file = [$fullFileName]"
	 if( ($validRet -eq 0) -or ($validRet -eq "FileTrusted") -or ($validRet -eq [Lenovo.CertificateValidation.TrustStatus]::FileTrusted))
	 {
	 	 return 1
	 }
	 return 0
}


# Note: ImpersonnateLoggedOnUser in exe
Function BatteryGaugeCtrlByApp($commandName)
{
	# Execute from dest dir
	$pathAppFile = "$PathPackageDirDest\$arch\BGHelper.exe"
	$pathDllFile = "$PathPackageDirDest\$arch\LenovoBatteryGaugePackage.dll"
	
	if((Test-Path -Path "$pathDllFile" -PathType Leaf) -and (Test-Path -Path "$pathAppFile" -PathType Leaf))
	{
		if(IsTrustedAssemblyFile($pathAppFile) -eq 1)
		{
			powershell $pathAppFile $commandName
			if ($? -eq $true)
			{
				Write-Log "BatteryGaugeCtrlByApp OK: ReturnCode=$LastExitCode, CmdName=$commandName"
				return 1
			}
		}
	}
	else
	{
		Write-Log "BatteryGaugeCtrlByApp file not found: CmdName=$commandName, AppPath=$pathAppFile, DllPath=$pathDllFile"
	}

	Write-Log "BatteryGaugeCtrlByApp($commandName) failed! ReturnCode=$LastExitCode"
	return 0
}

# Note: ImpersonnateLoggedOnUser in dll
Function BatteryGaugeCtrlByRundll32($commandName)
{
	#Param(
	#	[string]$commandName,
	#	[bool]$impersonnateLoggedOnUser = $True
	#)

	# Execute from dest dir
	$pathCmdFile = "$PathShortCutDir\$arch\$commandName.lnk"
	$pathDllFile = "$PathPackageDirDest\$arch\LenovoBatteryGaugePackage.dll"

	if((Test-Path -Path "$pathDllFile" -PathType Leaf) -and (Test-Path -Path "$pathCmdFile" -PathType Leaf))
	{
		if(IsTrustedAssemblyFile($pathDllFile) -eq 1)
		{
			# IMPORT: the 'blank space' MUST reserve!!!
			$commandParam = " $pathDllFile, " + $commandName
			powershell $applicationName $commandParam
			if ($? -eq $true)
			{
				Write-Log "BatteryGaugeCtrlByRundll32 OK: ReturnCode=$LastExitCode, CmdName=$commandName"
				return 1
			}
		}
	}
	else
	{
		Write-Log "BatteryGaugeCtrlByRundll32 file not found: CmdName=$commandName, CmdFile=$pathCmdFile, DllPath=$pathDllFile"
	}

	Write-Log "BatteryGaugeCtrlByRundll32($commandName) failed! ReturnCode=$LastExitCode"
	return 0
}

Function BatteryGaugeIconControlEx($commandName)
{
	$BGCtrlRet = BatteryGaugeCtrlByRundll32($commandName)
	if ($BGCtrlRet -eq 0)
	{
		$BGCtrlRet = BatteryGaugeCtrlByApp($commandName)	
	}

	return $BGCtrlRet
}

# ::***********************************************************************************************
# :: Definition: expand shortcut file
#$PathShortCutDir = "$env:ProgramData\Lenovo\Vantage\AddinData\$PackageName"

Function Expand-EnvironmentVariablesForLnkFile
{
    param([string]$modulePlatform, [string]$moduleFunction)

	if( -not(Test-Path "$PathShortCutDir\$modulePlatform") ) {
		New-Item "$PathShortCutDir\$modulePlatform\" -type directory
	}

    $shortCutFile = "$PathShortCutDir\$modulePlatform\$moduleFunction" + ".lnk"
	$argumentsList = "$PathPackageDirDest\$modulePlatform\LenovoBatteryGaugePackage.dll," + $moduleFunction
	$workingDir = "$PathPackageDirDest\$modulePlatform\"

    $wScriptShell = New-Object -ComObject WScript.Shell 
    $shortCut = $wScriptShell.CreateShortcut($shortCutFile) 
    $shortCut.TargetPath = [Environment]::ExpandEnvironmentVariables($applicationName)
    $shortCut.Arguments = [Environment]::ExpandEnvironmentVariables($argumentsList)
    $shortCut.WorkingDirectory = [Environment]::ExpandEnvironmentVariables($workingDir)
    $shortCut.Save() 
}

Function Expand-EnvironmentVariablesForLnkFileEx
{
	param([string]$moduleFunction)

	Expand-EnvironmentVariablesForLnkFile "x86" $moduleFunction
	Expand-EnvironmentVariablesForLnkFile "x64" $moduleFunction
}


# Kill BG processes directly. Only call when necessary.
Function StopBGProcessDirectly
{
	$PathExeRunFromPackageDirDest = "$PathPackageDirDest\.."
	Write-Log "Kill BG related processes, which run from: `"$PathExeRunFromPackageDirDest`" "
	
	(Get-Process | Select-Object Path,Id,Name | Where-Object {$_.Path -Ilike "$PathExeRunFromPackageDirDest*"}) | Stop-Process -Force

	$PathExeRunFromPackageShortCutDir = "$PathShortCutDir"
	(Get-Process | Select-Object Path,Id,Name | Where-Object {$_.Path -Ilike "$PathExeRunFromPackageShortCutDir*"}) | Stop-Process -Force
}

# Kill BG processes by taskkill
$TaskkillPath = "$env:SystemRoot\System32\taskkill.exe"

Function StopProcessByTaskkill
{
	Write-Log "Kill BG special processes if running"
	
	Start-Process -NoNewWindow -Wait -FilePath $TaskkillPath -ArgumentList "/F /T /IM HeartbeatMetrics.exe"
	Start-Process -NoNewWindow -Wait -FilePath $TaskkillPath -ArgumentList "/F /T /IM IdeaIntelligentCoolingMetrics.exe"
	Start-Process -NoNewWindow -Wait -FilePath $TaskkillPath -ArgumentList "/F /T /IM QuickSetting.exe"
	Start-Process -NoNewWindow -Wait -FilePath $TaskkillPath -ArgumentList "/F /T /IM QuickSettingEx.exe"
	Start-Process -NoNewWindow -Wait -FilePath $TaskkillPath -ArgumentList "/F /T /IM QSHelper.exe"
}


# BG should be excluded when device satisfies: {China + Lenovo/Idea brand + PCManager installed}
Function BatteryGaugeShouldBeExclude
{
	# read registry firstly in addin...
    $IsExclude = $False

    $miVantagePath = "$env:LOCALAPPDATA\Packages\E046963F.LenovoCompanion_k1h2ywk1493x8"
	$miVantageMVPPath = "$env:LOCALAPPDATA\Packages\E046963F.LenovoCompanionBeta_k1h2ywk1493x8"
    $miLEPath = "$env:LOCALAPPDATA\Packages\E046963F.LenovoSettingsforEnterprise_k1h2ywk1493x8"
    $IsInstallVantageLE = ((Test-Path $miVantagePath) -or (Test-Path $miVantageMVPPath) -or (Test-Path $miLEPath))
    if(-not($IsInstallVantageLE))
    {
		# need update???
        $miXmlFilePath = "$env:ProgramData\Lenovo\ImController\shared\MachineInformation.xml"
		if((Test-Path $miVantagePath))
		{
			$miXmlData = [xml](Get-Content $miXmlFilePath)
			$miCountry = ($miXmlData.MachineInformation.Country).ToLower()
			if($miCountry.Contains("cn"))
			{
				$miBrand = ($miXmlData.MachineInformation.Brand).ToLower()            
				$IsExclude = (($miBrand.Contains("idea")) -or ($miBrand.Contains("lenovo")))
			}
		}
		else
		{
			# read registry from addin???
		}

    }
    
    if($IsExclude)
    {
        #Is PCManager installed?
		$PcManagerRegPath = 'HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Lenovo\PcManager'
		$IsExclude = (Test-Path "Registry::$PcManagerRegPath")
    }

    return $IsExclude
}

# BG is installed?
Function BatteryGaugeIsInstalled
{
    $IsInstalled = $False
	$BGRegistryPath = 'HKEY_CLASSES_ROOT\CLSID\{E303DE81-073F-438A-B0D3-11C27526F607}'
	if(Test-Path "Registry::$BGRegistryPath")
	{
		$IsInstalled = $True
	}

    return $IsInstalled
}

# BG is pinned in taskbar?
Function IsBatteryGaugePinInTaskbar
{
	$IsBGPinned = 0

	$BgTaskList = tasklist /M "LenovoBatteryGaugePackage.dll"
	$ExplorerLike = $BgTaskList -like "explorer*"
	if($ExplorerLike -eq $true)
	{  
		$IsBGPinned = 1  
	}
	elseif($ExplorerLike -ne $false)
	{
		$BgInExplorer = (($ExplorerLike).ToLower()).Contains("explorer")
		if($BgInExplorer -eq $true)
		{  
			$IsBGPinned = 1  
		}
	}

	return $IsBGPinned
}



$RegSvr32Path = "$env:SystemRoot\System32\regsvr32.exe"
$RegAsmPath = "$PathPackageDirDest\RegAsm.exe"

# ::***********************************************************************************************
# :: Register new Lenovo Battery Gauge: PluginsContract.dll, LenovoBatteryGaugePackage.dll
# ::***********************************************************************************************
Function RegisterNewBatteryGauge
{
	# check directory first!!!!
	powershell $RegAsmPath "/silent $PathPackageDirDest\PluginsContract.dll"
	if($? -ne $true)
	{
		Write-Log "ReturnCode=$LastExitCode, powershell $RegAsmPath `"/silent $PathPackageDirDest\PluginsContract.dll`""
	}
	else
	{
		Write-Log "Register OK! powershell $RegAsmPath `"/silent $PathPackageDirDest\PluginsContract.dll`""
	}

	powershell $RegSvr32Path "/s $PathPackageDirDest\$arch\LenovoBatteryGaugePackage.dll"
	if($? -ne $true)
	{
		Write-Log "ReturnCode=$LastExitCode, powershell $RegSvr32Path `"/s $PathPackageDirDest\$arch\LenovoBatteryGaugePackage.dll`""
	}
	else
	{
		Write-Log "Register OK! powershell $RegSvr32Path `"/s $PathPackageDirDest\$arch\LenovoBatteryGaugePackage.dll`""
	}
}


# ::***********************************************************************************************
# Unregister new Lenovo Battery Gauge: LenovoBatteryGaugePackage.dll, PluginsContract.dll
# ::***********************************************************************************************
Function UnregisterNewBatteryGauge
{
	# check directory first!!!!
	powershell $RegSvr32Path "/s -u $PathPackageDirDest\$arch\LenovoBatteryGaugePackage.dll"
	if($? -ne $true)
	{
		Write-Log "ReturnCode=$LastExitCode, powershell $RegSvr32Path `"/s -u $PathPackageDirDest\$arch\LenovoBatteryGaugePackage.dll`""
	}

	powershell $RegAsmPath "/silent /u $PathPackageDirDest\PluginsContract.dll"
	if($? -ne $true)
	{
		Write-Log "ReturnCode=$LastExitCode, powershell $RegAsmPath `"/silent /u $PathPackageDirDest\PluginsContract.dll`""
	}
}


# ::***********************************************************************************************
# Uninstall old Lenovo Battery Gauge(which install by MSI). 
# Note: It does not exist in most Win10 devices now. So handle it with low priority.
# ::***********************************************************************************************
Function UninstallMsiOldBatteryGauge
{
	if (Get-Variable ProdCode64 -ErrorAction SilentlyContinue) {
		UninstallMsi($ProdCode64)
	}
	if (Get-Variable ProdCode32 -ErrorAction SilentlyContinue) {
		UninstallMsi($ProdCode32)
	}
	if (Get-Variable ProdCode64_OLD -ErrorAction SilentlyContinue) {
		UninstallMsi($ProdCode64_OLD)
	}
	if (Get-Variable ProdCode32_OLD -ErrorAction SilentlyContinue) {
		UninstallMsi($ProdCode32_OLD)
	}
}

# ::***********************************************************************************************
# :: Rename IMC Old Battery Gauge Package(install by IMC) file to ensure update successful
# ::***********************************************************************************************
Function RenameImcOldBatteryGaugePackageFile
{
	param([string]$fileName)

	Write-Log "Try to rename IMC Old Battery Gauge Package filename: [$fileName]"

	$fileNameBK = $fileName + "_bk"
	if( Test-Path -Path "$PathImcOldBGPackage\x86\$fileName" -PathType Leaf)
	{
		Remove-Item -Path "$PathImcOldBGPackage\x86\$fileNameBK" -Force *>&1 | Write-Log
		Rename-Item -Path "$PathImcOldBGPackage\x86\$fileName" -NewName "$fileNameBK" *>&1 | Write-Log
		New-Item -Path "$PathImcOldBGPackage\x86\$fileName" -Type File *>&1 | Write-Log
	}

	if( Test-Path -Path "$PathImcOldBGPackage\x64\$fileName" -PathType Leaf)
	{
		Remove-Item -Path "$PathImcOldBGPackage\x64\$fileNameBK" -Force *>&1 | Write-Log
		Rename-Item -Path "$PathImcOldBGPackage\x64\$fileName" -NewName "$fileNameBK" *>&1 | Write-Log
		New-Item -Path "$PathImcOldBGPackage\x64\$fileName" -Type File *>&1 | Write-Log
	}
}

# ::***********************************************************************************************
# Uninstall IMC Lenovo Battery Gauge Package(install by ImController). 
# ::***********************************************************************************************
Function UnpinImcOldBatteryGaugePackage
{
	$ImcRet = $false
	$ImcPackageDir = "$PathImcOldBGPackage\$arch"
	$ImcAppFile = "$ImcPackageDir\BGHelper.exe"
	$ImcDllFile = "$ImcPackageDir\LenovoBatteryGaugePackage.dll"
	$UnpinImcCommandName = "UnloadBatteryGaugeFromExplorer"
	if((Test-Path -Path "$ImcDllFile" -PathType Leaf) -and (Test-Path -Path "$ImcAppFile" -PathType Leaf))
	{
		if((IsTrustedAssemblyFile($ImcDllFile) -eq 1) -and (IsTrustedAssemblyFile($ImcAppFile) -eq 1))
		{
			powershell $ImcAppFile $UnpinImcCommandName
			if ($? -eq $true)
			{
				$ImcRet = $true
			}
			else
			{
				$ImcCommandParam = " $ImcDllFile, " + $UnpinImcCommandName
				powershell $applicationName $ImcCommandParam
				if ($? -eq $true)
				{
					$ImcRet = $true					
				}
			}
		}
	}
	Write-Log "Unpin IMC Old Battery Gauge Package result = [$ImcRet]: ReturnCode=$LastExitCode, CmdName=$UnpinImcCommandName"
}

Function UninstallImcOldBatteryGaugePackage
{
	if (Test-Path "$PathImcOldBGPackage\$arch\LenovoBatteryGaugePackage.dll")
	{
		StopProcessByTaskkill
		UnpinImcOldBatteryGaugePackage
		RenameImcOldBatteryGaugePackageFile "BGHelper.exe"
		RenameImcOldBatteryGaugePackageFile "Install.ps1"
		RenameImcOldBatteryGaugePackageFile "Uninstall.ps1"
	}
}
# ::***********************************************************************************************
# Register exe MaintenanceTask 
# ::***********************************************************************************************
Function RegisterMaintenanceTask
{
	# Delete old MaintenanceTask task
	$SchTasksPath = "$env:SystemRoot\System32\schtasks.exe"

	powershell $SchTasksPath /Delete /TN "\Lenovo\BatteryGauge\BatteryGaugeMaintenance" /F
	if($? -eq $true)
	{
		if( Test-Path -Path "$PathPackageDirDest\data\Maintenance.ps1" -PathType Leaf )
		{
			Remove-Item -Path "$PathPackageDirDest\data\Maintenance.ps1"
		}
	}
}


# ::***********************************************************************************************
# :: use "Trap" to handle terminating error( to force script running )
# ::***********************************************************************************************
trap 
{
	"An error trapped"
	$TrapError = $_.Exception
	$TrapErrorMsg = $TrapError.Message 
	$TrapLine = $_.InvocationInfo.ScriptLineNumber	
	Write-Log "Caught exception( trapped error ) at line[$TrapLine]: Msg= $TrapErrorMsg"
}

# ::***********************************************************************************************
# :: Begin installation
# ::    1. Update Maintenance Schedule Task firstly.
# ::    2. Check if BG conflict with PCM and skip this installation.
# ::    3. Check Bitness of OS, process
# ::    4. Create shortcut of rundll32 cmd. It's used for Pin/Unpin
# ::    5. Unpin & Unregister 3 old BG versions: (1) MSI package, (2) IMC package, (2) Old VS Addin.
# ::    6. Reigister & Pin new VS Addin.
# :: 
# ::***********************************************************************************************

Write-Log "Below logs come from: $PSCommandPath"

SetScriptFlagToReg "ScriptStart"

# replace with VS schedule task???
Write-Log "Register MaintenanceTask if necessary"
RegisterMaintenanceTask


# BG should be excluded from this device?
$BgInstalled = BatteryGaugeIsInstalled
if(BatteryGaugeShouldBeExclude)
{
	Write-Log "Exit... BatteryGauge should be excluded from device whom brand is Lenovo or Idea and PCManager has been installed(Geo = China(PRC))"

	# Delete BG if it has been installed
	if($BgInstalled -eq $True)
	{
		if (Test-Path "$PathPackageDirDest\$UninstallFileName")
		{
			Write-Log "Begin to uninstall BatteryGauge in the device which has installed PCManager...."
			$PSPATH="$env:SystemRoot\System32\WindowsPowerShell\v1.0\PowerShell.exe"
			Write-Log "Start-Process -NoNewWindow -Wait -FilePath $PSPATH -ArgumentList `"$PathPackageDirDest\$UninstallFileName`""
			Start-Process -NoNewWindow -Wait -FilePath $PSPATH -ArgumentList "$PathPackageDirDest\$UninstallFileName" *>&1 | Write-Log
		}
	}
	
	SetScriptFlagToReg "ScriptAbort_Exclude"

	Exit
}

# Does package match OS bitness???
Write-Log "OperatingSystem=[$OS_BITNESS bit], Process=[$PS_BITNESS bit]"
if ($PS_BITNESS -eq 32)
{
	if ($OS_BITNESS -eq 64)
	{
		Write-Log "Package bitness is 64 but process is 32.  Relaunching as 64"
		$PS64BITPATH="$env:SystemRoot\SysNative\WindowsPowerShell\v1.0\PowerShell.exe"
		Write-Log "Start-Process -NoNewWindow -Wait -FilePath $PS64BITPATH -ArgumentList `"$PSCommandPath`""
		Start-Process -NoNewWindow -Wait -FilePath $PS64BITPATH -ArgumentList "$PSCommandPath" *>&1 | Write-Log
		Write-Log "Completed re-running as 64 bit"

		SetScriptFlagToReg "ScriptAbort_BitMisMatch"

		Exit
	}
}
elseif ($PS_BITNESS -ne 64)
{
	Write-Log "Package bitness unknown, will exit."
}


# ::***********************************************************************************************
# Expand shortcut with absolute path for BG control
# ::***********************************************************************************************
Expand-EnvironmentVariablesForLnkFileEx "ShowBatteryGauge"
Expand-EnvironmentVariablesForLnkFileEx "HideBatteryGauge"
Expand-EnvironmentVariablesForLnkFileEx "UnpinFromTaskbar"
Expand-EnvironmentVariablesForLnkFileEx "UnloadBatteryGaugeFromExplorer"
Expand-EnvironmentVariablesForLnkFileEx "SetMenuItemNameofBatteryGauge"
Expand-EnvironmentVariablesForLnkFileEx "UpdateBatteryGaugeToastInfo"
Expand-EnvironmentVariablesForLnkFileEx "LaunchPinVantageToolbarToast"


# ::***********************************************************************************************
# :: [Uninstall old Lenovo Battery Gauge ]
# ::***********************************************************************************************
Write-Log "Uninstall old Lenovo Battery Gauge(which install by MSI). It might not exist"
UninstallMsiOldBatteryGauge


#::***********************************************************************************************
#:: [Check whether pinned battery gauge to taskbar previously]
#::***********************************************************************************************
$Pinned = 0
$SID = GetCurrentActiveUserSID	
New-PSDrive -PSProvider Registry -Name HKU -Root HKEY_USERS
$BgPinReg = (Get-ItemProperty -Path HKU:$SID\SOFTWARE\Lenovo\BatteryGauge -Name "ShowInTaskbar" -ErrorAction SilentlyContinue).ShowInTaskbar
	
## Is BG pinned ? Check it in taskbar
$BgPinTaskbar = IsBatteryGaugePinInTaskbar	
if(($BgPinReg -eq 1) -or ($BgPinTaskbar -eq 1))
{
	$Pinned = 1
}

Write-Log "The BatteryGauge current display status: BgPinReg = $BgPinReg, BgPinTaskbar=$BgPinTaskbar"
#Remove-PSDrive -Name HKU


# ::***********************************************************************************************
# :: [Kill active BG processes]:
# ::  QuickSetting.exe,QuickSettingEx.exe,HeartbeatMetrics.exe,SetThinkTouchPad.exe....]
# ::***********************************************************************************************
Write-Log "Unload old QSHelper directly"
Start-Process -NoNewWindow -Wait -FilePath $TaskkillPath -ArgumentList "/T /IM QSHelper.exe"

StopBGProcessDirectly

# uninstall old package & old addin!!!
Write-Log "Uninstall old Lenovo Battery Gauge(install by IMC)."
UninstallImcOldBatteryGaugePackage

Write-Log "Unload old BatteryGauge Addin(VS) from explorer"
BatteryGaugeIconControlEx($UnloadBg)

Write-Log "Unregister old BatteryGauge Addin(VS) related components"
UnregisterNewBatteryGauge


# ::***********************************************************************************************
# :: [Register PluginsContract.dll,Register LenovoBatteryGaugePackage.dll ]
# ::***********************************************************************************************
Write-Log "Register new BatteryGauge Add(VS) related components"
RegisterNewBatteryGauge


# ::***********************************************************************************************
# :: [Copy QSHelper to AddinData folder]
# ::***********************************************************************************************
Write-Log "Copy-Item `"$PSScriptRoot\x64\*`" `"$PathShortCutDir\x64\`" -force -recurse"
Copy-Item "$PSScriptRoot\x64\*" "$PathShortCutDir\x64\" -force -recurse
Copy-Item "$PSScriptRoot\x86\*" "$PathShortCutDir\x86\" -force -recurse



# ::***********************************************************************************************
# :: [ Pin to task bar if needed]
# ::***********************************************************************************************
Write-Log "installing param is: $Pinned"
if ($Pinned -eq 1)
{
	$retCtrl = BatteryGaugeIconControlEx($ShowBg)
	if($retCtrl -eq 0)
	{
		Write-Log "Try to show BatteryyGauge again..., ReturnCode=$LastExitCode"
		Start-Sleep -Milliseconds 400	
		$retCtrl = BatteryGaugeIconControlEx($ShowBg)
	}
	Write-Log "Show BatteryGauge on taskbar, show = $retCtrl, ReturnCode=$LastExitCode"

	New-ItemProperty -Path HKU:$SID\SOFTWARE\Lenovo\BatteryGauge -Name "ShowInTaskbar" -Value $Pinned -PropertyType DWORD -Force
}


Remove-PSDrive -Name HKU

Write-Log "Details of dest package info(new version)-------------------------"
PrintDestPackageDetails

Write-Log "Install successful!"
SetScriptFlagToReg "ScriptStop"

Exit

# SIG # Begin signature block
# MIItqAYJKoZIhvcNAQcCoIItmTCCLZUCAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCC0CclqS1byMV1i
# 97AUvzxowpCbRzF3DthRYkSCjcyWZKCCJqswggWNMIIEdaADAgECAhAOmxiO+dAt
# 5+/bUOIIQBhaMA0GCSqGSIb3DQEBDAUAMGUxCzAJBgNVBAYTAlVTMRUwEwYDVQQK
# EwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20xJ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