# VARIABLES
#------------------------------------------------
$Argument=$args[0]
$Argument2=$args[1]
Write-Host "Passed Arguments: $Argument"
Write-Host "Passed Arguments2: $Argument2"

$ParentFolder = $(get-item $PSScriptRoot).parent.FullName
# $Logfile = "C:\$(gc env:computername)-Windows-Toolbox.log"
$Logfile = "C:\Windows-Setup.log"
$ChocoAppListFP = "C:\Users\${env:USERNAME}\ChocolateyPackageList.config"

# Write-Host $ParentFolder
# Write-Host "$PSScriptRoot"

# FUNCTIONS
#------------------------------------------------
Function Set-Speaker($Volume){$wshShell = new-object -com wscript.shell;1..50 | % {$wshShell.SendKeys([char]174)};1..$Volume | % {$wshShell.SendKeys([char]175)}}

Function LogWrite
{
   Param ([string]$logstring)

   $currentDateTime = Get-Date
   $formattedDateTime = $currentDateTime.ToString("yyyyMMdd-HHmmss")

   Add-content $Logfile -value "${formattedDateTime}: ${logstring}"
   Write-Host $logstring
}


# MAIN SCRIPT
#------------------------------------------------
if($Argument2) {
    LogWrite "Renaming Computer to $Argument2"
    Rename-Computer -NewName "$Argument2" -DomainCredential ity
}

if($Argument -like '*SetTimezone*') {
    LogWrite "Setting Time Zone to Eastern Standard Time"
    Set-TimeZone -Name "Eastern Standard Time"
}


if($Argument -like '*MeshCentral*') {
    LogWrite "Installing MeshCentral"
    Start-Process -FilePath "${ParentFolder}\MeshCentral\InstallMeshCentral.bat"
}


# CHOCOLATEY
if($Argument -like '*choco*') {

    # https://chocolatey.org/install
    LogWrite "Installing Chocolatey"
    [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))

}

if($Argument -like '*ChocoUpgrade*') {

    # https://chocolatey.org/install
    LogWrite "Updating Chocolatey"
    choco upgrade all -y 
    # [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
}

if($Argument -like '*ChocoAutoUpgrade*') {

    # https://chocolatey.org/install
    $UpdateHour=(1..4 | get-random)
    LogWrite "Installing Chocolatey Auto Upgrade Package with Scheduled Time for Sunday at ${UpdateHour} AM"
    choco install choco-upgrade-all-at --params "'/WEEKLY:yes /DAY:SUN /TIME:0${UpdateHour}:00 /ABORTTIME:06:00'" -y
    # [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
}

if($Argument -like '*VoidtoolsEverything*') {

    # https://chocolatey.org/install
    LogWrite "Installing Voidtools Everything"
    choco install -y everything
}

if($Argument -like '*EverythingConfig*') {

    # https://chocolatey.org/install
    # LogWrite "Installing Voidtools Everything"
    # choco install -y everything

    LogWrite "Copying Voidtools Everything Config"

    # Kill everything process before copying config file
    Stop-Process -Name "Everything" -Force

    $EverythingConfigDir = "C:\Users\" + ${env:USERNAME} + "\AppData\Roaming\Everything"

    # copy to current user
    Copy-Item "${ParentFolder}\Everything\Everything.ini" -Destination "${EverythingConfigDir}\Everything.ini"

    # copy to default user for all future created profiles
    New-Item -Path "C:\Users\Default\AppData\Roaming\Everything\" -ItemType Directory
    Copy-Item "${ParentFolder}\Everything\Everything.ini" -Destination "C:\Users\Default\AppData\Roaming\Everything\Everything.ini"

    # Start-Process -FilePath "C:\Program Files\Everything\Everything.exe"

    # not sure if need to split these up or can be in 1 line
    & "C:\Program Files\Everything\Everything.exe" -rescan-all -install-all-users-start-menu-shortcuts -install-service -install-run-on-system-startup -install-folder-context-menu
}


if($Argument -like '*Bitwarden*') {
    LogWrite "Copying Bitwarden-Updater file to current and \Default\ user"
    # Copy bitwarden-updater file to disable bitwarden auto updates so users don't get annoying prompts that they can't take action on
    # copy to default user folder so users that log in for the first time use this file
    xcopy "${ParentFolder}\Bitwarden\bitwarden-updater" "C:\Users\Default\AppData\Local\" /y

    # copy to current user folder
    $BitwardenUserUpdaterFolder = "C:\Users\" + ${env:USERNAME} + "\AppData\Local\"
    Write-Host "Copying Locked Bitwarden User Update Folder to:" ${BitwardenUserUpdaterFolder}
    xcopy "${ParentFolder}\Bitwarden\bitwarden-updater" "${BitwardenUserUpdaterFolder}" /y

    LogWrite "Installing Bitwarden"
    # install for all users with /allusers, as per: https://community.chocolatey.org/packages/bitwarden
    choco install -y bitwarden -ia "/allusers "  
}
if($Argument -like '*pdfxchange*') {

    LogWrite "Installing PDF-XChange"
    choco install pdfxchangeeditor -y  
}

if($Argument -like '*adobereader*') {

    LogWrite "Installing Adobe Reader"
    choco install adobereader -y  
}

if($Argument -like '*GoogleChrome*') {

    LogWrite "Installing Google Chrome"
    # install for all users with /allusers, as per: https://community.chocolatey.org/packages/bitwarden
    choco install googlechrome -y  
}


if($Argument -like '*ShareX*') {

    LogWrite "Installing ShareX"
    choco install -y sharex

    # kill shareX process
    Stop-Process -Name "ShareX" -Force


    $ShareXConfigDir = "C:\Users\" + ${env:USERNAME} + "\Documents\ShareX"
    New-Item -Path "${ShareXConfigDir}" -ItemType Directory
    xcopy "${ParentFolder}\ShareX\ShareX" "${ShareXConfigDir}" /y
    # Copy-Item "${ParentFolder}\Everything\Everything.ini" -Destination "${EverythingConfigDir}\Everything.ini"

    # create config folder on Default user account and copy sharex config files to it
    # Whenever a new user is created on a computer, items from the default account get copied to their account.
    $ShareXConfigDir = "C:\Users\Default\Documents\ShareX"
    New-Item -Path "${ShareXConfigDir}" -ItemType Directory
    xcopy "${ParentFolder}\ShareX\ShareX" "${ShareXConfigDir}" /y

    # create screenshots folder for current user
    $CurrentUserScreenshotsFolder = "C:\Users\" + ${env:USERNAME} + "\Pictures\Screenshots"
    New-Item -Path "${CurrentUserScreenshotsFolder}" -ItemType Directory

    # create screenshots folder in default user account
    New-Item -Path 'C:\Users\Default\Pictures\Screenshots' -ItemType Directory

    # create a startup folder in default account
    New-Item -Path 'C:\Users\Default\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\'

    # copy sharex shortcut link to default profile's startup folder
    xcopy "${ParentFolder}\ShareX\ShareXStartupFolderShortcut\ShareX.lnk" "C:\Users\Default\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\" /y


    # start sharex so that configuration in documents folder gets pulled in
    # Start-Process -Filepath "C:\Program Files\ShareX\ShareX.exe"
}


if($Argument -like '*DWGSeePro*') {

    LogWrite "Installing DWGSeePro"
    & "${ParentFolder}\DWGSeePro\DWGSeePro2023_Installer.exe"
}

if($Argument -like '*ZabbixAgent*') {

    if($Argument -like '*chocoZabbixAgent*') {

        LogWrite "Installing Zabbix Agent using chocolatey"
        choco install -y zabbix-agent
    }
    else {
        Start-Process -Filepath "${ParentFolder}\Zabbix\zabbix_agent.msi" -Wait
    }

    LogWrite "Allowing Inbound Zabbix Agent Port through Firewall"
    # https://gist.github.com/nidr0x/00d47c75b28e8492b5b936ff02b0a4d6
    netsh advfirewall firewall add rule name="Open Zabbix agentd port 10050 inbound" dir=in action=allow protocol=TCP localport=10050

    LogWrite "Copying Zabbix-Agent Configuration"
    Copy-Item "${ParentFolder}\Zabbix\zabbix_agentd.conf" -Destination "C:\ProgramData\zabbix\zabbix_agentd.conf" -Force

    LogWrite "Restarting Zabbix Agent Service"
    Restart-Service -Name "Zabbix Agent"

    # Append hostname and IP address to .txt file for easy copy and paste into zabbix
    LogWrite "Appending Hostname and Address to \\smb\General\Zabbix-Devices.txt"
    $hostname = $env:COMPUTERNAME
    $ipAddress = (ipconfig /all)
    Add-Content -Path "\\smb\General\Zabbix-Devices.txt" -Value "$hostname  $ipAddress"

}


if($Argument -like '*drawio*') {

    LogWrite "Installing draw.io"
    choco install -y drawio 
}


if($Argument -like '*Wireguard*') {

    LogWrite "Installing Wireguard"
    choco install -y wireguard 
}


if($Argument -like '*NoMachine-*') {

    LogWrite "Installing NoMachine"
    choco install -y nomachine
    # LogWrite "Removing nxplayer.exe"
    # Remove-Item -Path 'C:\Program Files (x86)\NoMachine\bin\nxplayer.exe'
    Remove-Item -Path 'C:\Users\Public\Desktop\NoMachine.lnk'


    # https://kb.nomachine.com/AR05M00847
    # disable auto update checks since chocolatey is used
    # Disable screen blanking when remoting in
    # do not lock screen when disconnecting

}   

if($Argument -like '*NoMachineConfig*') {

    LogWrite "Copying NoMachine Configuration"

    If (Test-Path -Path "C:\Program Files (x86)\NoMachine"){
        $NoMachineDirectory = "C:\Program Files (x86)\NoMachine"
    }
    else {
        $NoMachineDirectory = "C:\Program Files\NoMachine"
    }

    # https://kb.nomachine.com/AR05M00847
    # disable auto update checks since chocolatey is used
    Copy-Item "${ParentFolder}\NoMachine\server.cfg" -Destination "${NoMachineDirectory}\etc\server.cfg"

    # restart nomachine server
    LogWrite "Restarting NoMachine Service"
    & "${NoMachineDirectory}\bin\nxserver.exe" --restart

}

if($Argument -like '*Office365*') {
    # Office Deployment Tool XML File editing:
    # https://answers.microsoft.com/en-us/msoffice/forum/all/installing-only-particular-office-365-programs/9ebb27d4-1084-42e7-b84a-c5dd76e9232c
    # Current config skips: Grove, Lync, SkypeforBusiness, and Access

    LogWrite "Installing Office365"

    $arg1 = "${ParentFolder}\Office365\ODT_x64\setup.exe"
    LogWrite $arg1
    $arg2 = "/configure"
    LogWrite $arg2
    $arg3 = "${ParentFolder}\Office365\ODT_x64\configuration-Office365-x64Business.xml"
    LogWrite $arg3

    & $arg1 $arg2 $arg3


    # TEMPORARY until i can figure out why the variables won't work
    # & \\smb\Toolbox\Installs\Office365\ODT_x64\setup.exe /configure \\smb\Toolbox\Installs\Office365\ODT_x64\configuration-Office365-x64Business.xml

}


if($Argument -like '*Office32bit*') {

    LogWrite "Installing Office 365 32bit"
    Start-Process -Filepath "${ParentFolder}\Office365\Office365Setup_32BIT.exe"
}

if($Argument -like '*Parcview*') {

    LogWrite "Installing Parcview"

    # if parcview not installed, install it
    if(!(Test-Path -Path "C:\Program Files (x86)\Capstone\PARCView\PARCView.exe")){

        # start the installer
        & "\\smb\Parcview\PARCView Silent No Launch.msi"
        
        LogWrite "Waiting 5 minutes for install to complete"
        powershell Start-Sleep -s 300

        # Start-Process -Filepath "${ParentFolder}\PARCview 5.0.0.6\PARCView Silent No Launch.msi"
        # LogWrite "Sleeping 5 minutes for install to complete"
        # powershell Start-Sleep -s 300
    }

    # Allow inbound traffic firewall rule
    New-NetFirewallRule -DisplayName "PARCView" -Direction Inbound -Program "C:\Program Files (x86)\Capstone\PARCView\PARCView.exe" -Action Allow

    LogWrite "Starting Parcview"
    Start-Process -Filepath "C:\Program Files (x86)\Capstone\PARCView\PARCView.exe"

}

if($Argument -like '*PVConfig*') {
    LogWrite "Copying Configuration File"
    # Create config folder
    New-Item -Path 'C:\ProgramData\Capstone\PARCView' -ItemType Directory
    
    # copy configuration file
    Copy-Item "\\smb\Parcview\program files\Capstone\PARCView\PVConfig.XML" -Destination "C:\ProgramData\Capstone\PARCView\PVConfig.XML" -Force
}


if($Argument -like '*BGInfo*') {

    LogWrite "Setting BGInfo Wallpaper"
    & "${ParentFolder}\BGInfo\Bginfo.exe" "${ParentFolder}\BGInfo\BGInfo_Template.bgi" "/NOLICPROMPT" "/TIMER:0"

}

if($Argument -like '*BGBootInfo*') {

    LogWrite "Setting BGInfo on boot"
    New-Item -Path "C:\Scripts\" -ItemType Directory

    LogWrite "${ParentFolder}\BGInfo" "C:\Scripts\" 
    xcopy /E /y "${ParentFolder}\BGInfo" "C:\Scripts\" 

    # copy to current user
    Copy-Item "${ParentFolder}\BGInfo\SystemStartup_BGInfo.lnk" -Destination "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\SystemStartup_BGInfo.lnk" -Force
}


if($Argument -like '*OOSU*') {
    Start-Process -FilePath "${ParentFolder}\OOSU10\OOSU10.exe" -ArgumentList "${ParentFolder}\OOSU10\ooshutup10.cfg"
}


if($Argument -like '*urBackup*') {
    LogWrite "Installing urBackup"
    & "${ParentFolder}\urBackup\UrBackup Client 2.5.25-cbt(x64).msi" /quiet
}

if($Argument -like '*DisplayTime30*') {
    LogWrite "Changing Display Timeout to 30 mins"
    powercfg -change -monitor-timeout-ac 30
    powercfg -change -monitor-timeout-dc 30

    LogWrite "Changing Hibernate to never, and 30 mins if on battery"
    powercfg -change -standby-timeout-ac 0
    powercfg -change -standby-timeout-dc 30

}


if($Argument -like '*DisplayTime0*') {
    LogWrite "Changing Display Timeout to never"
    powercfg -change -monitor-timeout-ac 0
    powercfg -change -monitor-timeout-dc 30

    LogWrite "Changing Hibernate to never, and 30 mins if on battery"
    powercfg -change -standby-timeout-ac 0
    powercfg -change -standby-timeout-dc 30
}


if($Argument -like '*AutoLogon*') {
    LogWrite "Starting AutoLogon"
    Start-Process -Filepath "${ParentFolder}\AutoLogon\Autologon64.exe"

}

if($Argument -like '*Debloat*') {
    # Clear public desktop folder
    $Folder = "C:\Users\Public\Desktop\"
    Get-ChildItem $Folder | Remove-Item -recurse -Force
    LogWrite "Content of $Folder Deleted.." -BackgroundColor Green -ForegroundColor Black
}


## Printers
if($Argument -like '*Printer_TM06SUPICANONCOLOR*') {
    LogWrite "Installing Printer: TM06SUPI - CANON (COLOR) AND TM06SUPI - CANON (COLOR)"
    Start-Process -Filepath "\\rosewood\TM06SUPI - CANON (COLOR)"
    # powershell Start-Sleep -s 60
    LogWrite "Installing Printer: TM06SUPI - CANON (COLOR) AND TM06SUPI - CANON (BW)"
    Start-Process -Filepath "\\rosewood\TM06SUPI - CANON (BW)"
}

if($Argument -like '*PrinterDrivers*') {
    LogWrite "Installing Printer: MGMT - SHARP"
    Start-Process -Filepath "\\rosewood\MGMT - SHARP"

    LogWrite "Installing Printer: MNT - SHARP"
    Start-Process -Filepath "\\rosewood\MNT - SHARP"
}

if($Argument -like '*MGMTSHARP*') {
    LogWrite "Installing Printer: MGMT - SHARP"
    Start-Process -Filepath "\\rosewood\MGMT - SHARP"
}

if($Argument -like '*Printer_MGMTHPColor*') {
    LogWrite "Installing Printer: MGMT - HP (Color)"
    Start-Process -Filepath "\\rosewood\MGMT - HP (Color)"
    Start-Process -Filepath "\\rosewood\MGMT - HP (BW)"
}





if($Argument -like '*SaneWindowsUpdates*') {
 # pulled from Titus WinUtil
 # https://github.com/ChrisTitusTech/winutil/blob/main/winutil.ps1
 LogWrite "Disabling driver offering through Windows Update..."
 If (!(Test-Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\Device Metadata")) {
    New-Item -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\Device Metadata" -Force | Out-Null
}
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\Device Metadata" -Name "PreventDeviceMetadataFromNetwork" -Type DWord -Value 1
If (!(Test-Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\DriverSearching")) {
    New-Item -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\DriverSearching" -Force | Out-Null
}
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\DriverSearching" -Name "DontPromptForWindowsUpdate" -Type DWord -Value 1
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\DriverSearching" -Name "DontSearchWindowsUpdate" -Type DWord -Value 1
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\DriverSearching" -Name "DriverUpdateWizardWuSearchEnabled" -Type DWord -Value 0
If (!(Test-Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate")) {
    New-Item -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate" | Out-Null
}
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate" -Name "ExcludeWUDriversInQualityUpdate" -Type DWord -Value 1
LogWrite "Disabling Windows Update automatic restart..."
If (!(Test-Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU")) {
    New-Item -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU" -Force | Out-Null
}
LogWrite "Disabling Auto Reboot for Updates"
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "NoAutoRebootWithLoggedOnUsers" -Type DWord -Value 1
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU" -Name "AUPowerManagement" -Type DWord -Value 0

LogWrite "Defering Feature Updates for 1 year and defering windows updates to sane levels"
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\WindowsUpdate\UX\Settings" -Name "BranchReadinessLevel" -Type DWord -Value 20
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\WindowsUpdate\UX\Settings" -Name "DeferFeatureUpdatesPeriodInDays" -Type DWord -Value 365
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\WindowsUpdate\UX\Settings" -Name "DeferQualityUpdatesPeriodInDays " -Type DWord -Value 4

}



if($Argument -like '*CleanW11StartMenu*') {
    $Layout = 'AppData\Local\Packages\Microsoft.Windows.StartMenuExperienceHost_cw5n1h2txyewy\LocalState'
    Get-ChildItem 'C:\Users' | ForEach-Object { Remove-Item "C:\Users\$($_.Name)\$Layout" -Recurse -Force -ErrorAction Ignore }

    xcopy "${ParentFolder}\W11StartMenu\start2.bin" "C:\Users\Default\AppData\Local\Packages\Microsoft.Windows.StartMenuExperienceHost_cw5n1h2txyewy\LocalState\" /y

    if ($env:USERNAME -ne 'defaultuser0') { Stop-Process -Name explorer -Force }

}

if($Argument -like '*AddWifiNetwork*') {
    netsh wlan add profile filename="${ParentFolder}\Wifi\Wifi-Settings.xml"
}



if($Argument -like '*DisableLockScreen*') {
    LogWrite "Importing Disable Lockscreen Registory Key"
    reg import ${ParentFolder}\PowerShell\DisableLockScreen.reg
}


if($Argument -like '*SpeakerTest*'){
    Set-Speaker -Volume 5
    Start-Process https://www.youtube.com/watch?v=LDU_Txk06tM
}
if($Argument -like '*MicrophoneTest*'){
    Start-Process https://mictests.com/
}

# Join Domain 
if($Argument -like '*DomainJoin*') {
    LogWrite "Joining Domain"

    Add-Computer -DomainName FULLDOMAINNAME
}


if($Argument -like '*DellCU*') {
    $Manufacturer=Get-CimInstance -ClassName Win32_ComputerSystem | Select-Object "Manufacturer"

    if($Manufacturer -like '*Dell*') {

        LogWrite "Checking if running on Dell Hardware"


        LogWrite "Installing Dell Command Update"
        choco install -y dellcommandupdate

        # chocolatey can instlal dell command update to Program Files or Progam files (x86)
        # starting sometime around 5/18/2023, it seems to install to Program Files
        If (Test-Path -Path "C:\Program Files (x86)\Dell\CommandUpdate\dcu-cli.exe"){
            $DCUCLIPath = "C:\Program Files (x86)\Dell\CommandUpdate\dcu-cli.exe"
        }
        else {
            $DCUCLIPath = "C:\Program Files\Dell\CommandUpdate\dcu-cli.exe"
        }


        # Disable automatic update checks
        # https://dl.dell.com/content/manual13608255-dell-command-update-version-4-x-reference-guide.pdf?language=en-us&ps=true
        If (Test-Path -Path "${DCUCLIPath}") {
            # Set weekly update check
            # Start-Process -FilePath "C:\Program Files (x86)\Dell\CommandUpdate\dcu-cli.exe" -ArgumentList "/configure", "-scheduleWeekly"
            # Start dell command update so you can disable automatic update checking manually
            # Start-Process -Filepath "C:\Program Files (x86)\Dell\CommandUpdate\DellCommandUpdate.exe"

            # set dell CU update manual through cli utility
            & "${DCUCLIPath}" /configure -scheduleManual

            # Run utility and install updates and disable automatic reboot for the run
            & "${DCUCLIPath}" /ApplyUpdates -reboot=disable

        }
        else {
            LogWrite "Dell Command Update Failed to Install.  - ${DCUCLIPath} - doens't exist"
        }
    }
    else {
        LogWrite "Skipping Dell Command Update install as this is not a Dell Machine"
    }

}


# Update windows through powershell
if($Argument -like '*UpdateWindows*') {

    # LogWrite "Muting System Volume"
    LogWrite "Muting System Volume"
    $obj = new-object -com wscript.shell
    $obj.SendKeys([char]173)


    LogWrite "Changing Display Timeout to 30 mins for updating Windows"
    powercfg -change -monitor-timeout-ac 30
    powercfg -change -monitor-timeout-dc 30

    LogWrite "Installing Windows Updates through PowerShell"
    
    # https://pureinfotech.com/install-windows-10-update-powershell/
    # Install-Module PSWindowsUpdate -Force
    # Get-WindowsUpdate
    # Install-WindowsUpdate -Force
    # Get-WindowsUpdate -AcceptAll -Install -AutoReboot

    Install-PackageProvider -Name NuGet -Force
    Install-Module PSWindowsUpdate -Force 
    # Add-WUServiceManager -MicrosoftUpdate -Force 
    Install-WindowsUpdate -MicrosoftUpdate -AcceptAll -AutoReboot # | Out-File "C:\($env.computername)-MSUpdates.log" -Force
    powershell Start-Sleep -s 20

    # install twice as sometimes there is more updates after running it for the first time.
    Install-WindowsUpdate -MicrosoftUpdate -AcceptAll -AutoReboot # | Out-File "C:\($env.computername)-MSUpdates.log" -Force

    # wuauclt /detectnow /updatenow
    # control update
    # UsoClient /startScan /StartDownload /StartInstall
    # control update

    # wait 1 minute before continuing in case windows needs to restart
    LogWrite "Waiting 1 minute in case a PC reboot is needed"
    powershell Start-Sleep -s 60

}

if($Argument -like '*SilentSystemUpdate*') {

    if($Argument -like '*Staggered*') {
        $SleepLength=(300..18000 | get-random) # between 5 minutes and 5 hours

        LogWrite "Sleeping ${SleepLength} seconds before launching System Updates"

        powershell start-sleep -s ${SleepLength}
    }

    # OutputPath = 'C:\Users\%A_Username%\Syncthing\Configurations\Chocolatey\%A_ComputerName%_ChocolateyApps.config'

    LogWrite "Chocolatey: Enabling allowGlobalConfirmation"
    choco feature enable -n=allowGlobalConfirmation
    # choco feature enable -n useFipsCompliantChecksums

    LogWrite "Chocolatey: Upgrading all Packages"
    choco upgrade all

    LogWrite "Chocolatey: Installing pswindowsupdate"
    choco install pswindowsupdate

    # Add-WUServiceManager -ServiceID 7971f918-a847-4430-9279-4a52d1efe18d -Confirm:$false

    LogWrite "Chocolatey: Installing Windows Updates without restarting"
    Install-WindowsUpdate -MicrosoftUpdate -AcceptAll 
    Get-WuInstall -AcceptAll -IgnoreReboot

    LogWrite "Checking if running on Dell Hardware"
    $Manufacturer=Get-CimInstance -ClassName Win32_ComputerSystem | Select-Object "Manufacturer"

    if($Manufacturer -like '*Dell*') {

        LogWrite "Installing Dell Command Update"
        choco install -y dellcommandupdate

        # chocolatey can instlal dell command update to Program Files or Progam files (x86)
        # starting sometime around 5/18/2023, it seems to install to Program Files
        If (Test-Path -Path "C:\Program Files (x86)\Dell\CommandUpdate\dcu-cli.exe"){
            $DCUCLIPath = "C:\Program Files (x86)\Dell\CommandUpdate\dcu-cli.exe"
        }
        else {
            $DCUCLIPath = "C:\Program Files\Dell\CommandUpdate\dcu-cli.exe"
        }


        # Disable automatic update checks
        # https://dl.dell.com/content/manual13608255-dell-command-update-version-4-x-reference-guide.pdf?language=en-us&ps=true
        If (Test-Path -Path "${DCUCLIPath}") {
            # Set weekly update check
            # Start-Process -FilePath "C:\Program Files (x86)\Dell\CommandUpdate\dcu-cli.exe" -ArgumentList "/configure", "-scheduleWeekly"
            # Start dell command update so you can disable automatic update checking manually
            # Start-Process -Filepath "C:\Program Files (x86)\Dell\CommandUpdate\DellCommandUpdate.exe"

            # set dell CU update manual through cli utility
            & "${DCUCLIPath}" /configure -scheduleManual

            # Run utility and install updates and disable automatic reboot for the run
            & "${DCUCLIPath}" /ApplyUpdates -reboot=disable

        }
        else {
            LogWrite "Dell Command Update Failed to Install.  - ${DCUCLIPath} - doesn't exist"
        }
    }
    else {
        LogWrite "Skipping Dell Command Update Installation and Updates as this is not a Dell Machine"
    }


    # export chocolatey package list to User's Folder so it gets backed up with urBackup
    LogWrite "Exporting Chocolatey Package list to: ${ChocoAppListFP}"
    choco export -o="${ChocoAppListFP}" --allowunofficial

    # Clean all shortcuts from Public Desktop
    LogWrite "Removing all Desktop Shortcuts from \Users\Public\Desktop"
    Get-ChildItem 'C:\Users\Public\Desktop' | Remove-Item -Force -Recurse
}




if($Argument -like '*Debloat*') {


    # https://stackoverflow.com/questions/45152335/unpin-the-microsoft-edge-and-store-taskbar-shortcuts-programmatically?answertab=trending#tab-top
    function Unpin-App([string]$appname) {
        ((New-Object -Com Shell.Application).NameSpace('shell:::{4234d49b-0245-4df3-b780-3893943456e1}').Items() |
            ?{$_.Name -eq $appname}).Verbs() | ?{$_.Name.replace('&','') -match 'Unpin from taskbar'} | %{$_.DoIt()}
    }
    LogWrite "Unpinning Useless Taskbar Shortcuts"
    Unpin-App("Microsoft Store")
    Unpin-App("Mail")
    Unpin-App("Chat")

    # https://www.brankovucinec.com/powershell-reclaim-windows-10/
    # Hide Task View button
    LogWrite "Hiding Task View button..."
    Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" -Name "ShowTaskViewButton" -Type DWord -Value 0

    # https://www.brankovucinec.com/powershell-reclaim-windows-10/
    # Hide Search button / box
    LogWrite "Hiding Search Box / Button..."
    Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Search" -Name "SearchboxTaskbarMode" -Type DWord -Value 0

    # hide cortana Button
    # https://winaero.com/hide-cortana-button-taskbar-windows-10/
    LogWrite "Hiding Cortana Button"
    Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" -Name "ShowCortanaButton" -Type DWord -Value 0



    # Disable News Feeds 
    # pulled from Titus WinUtil
    # https://github.com/ChrisTitusTech/winutil/blob/main/winutil.ps1
    # LogWrite "Disable News and Interests"
    # https://answers.microsoft.com/en-us/windows/forum/all/hide-news-and-interests-for-new-users/feaeddbb-a3ee-48eb-b56a-e3497df07a28
    # Set-ItemProperty -Path "HKCU:\SOFTWARE\Policies\Microsoft\Windows\Windows Feeds" -Name "HeadlinesOnboardingComplete" -Type DWord -Value 1
    
    # Set-ItemProperty -Path "HKCU:\SOFTWARE\Policies\Microsoft\Windows\Windows Feeds" -Name "EnableFeeds" -Type DWord -Value 0
    # Remove "News and Interest" from taskbar
    # Set-ItemProperty -Path  "HKCU:\Software\Microsoft\Windows\CurrentVersion\Feeds" -Name "ShellFeedsTaskbarViewMode" -Type DWord -Value 2

    # https://www.brankovucinec.com/powershell-reclaim-windows-10/
    # Disable Cortana
    LogWrite "Disabling Cortana..."
    If (!(Test-Path "HKCU:\Software\Microsoft\Personalization\Settings")) {
        New-Item -Path "HKCU:\Software\Microsoft\Personalization\Settings" -Force | Out-Null
    }
    Set-ItemProperty -Path "HKCU:\Software\Microsoft\Personalization\Settings" -Name "AcceptedPrivacyPolicy" -Type DWord -Value 0
    If (!(Test-Path "HKCU:\Software\Microsoft\InputPersonalization")) {
        New-Item -Path "HKCU:\Software\Microsoft\InputPersonalization" -Force | Out-Null
    }
    Set-ItemProperty -Path "HKCU:\Software\Microsoft\InputPersonalization" -Name "RestrictImplicitTextCollection" -Type DWord -Value 1
    Set-ItemProperty -Path "HKCU:\Software\Microsoft\InputPersonalization" -Name "RestrictImplicitInkCollection" -Type DWord -Value 1
    If (!(Test-Path "HKCU:\Software\Microsoft\InputPersonalization\TrainedDataStore")) {
        New-Item -Path "HKCU:\Software\Microsoft\InputPersonalization\TrainedDataStore" -Force | Out-Null
    }
    Set-ItemProperty -Path "HKCU:\Software\Microsoft\InputPersonalization\TrainedDataStore" -Name "HarvestContacts" -Type DWord -Value 0

    # Remove Meet-Now icon
    If (!(Test-Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer")) {
        New-Item -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer" -Force | Out-Null
    }

    Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer" -Name "HideSCAMeetNow" -Value 1

    # Uninstall Bloatware
    # pulled from Titus WinUtil
    # https://github.com/ChrisTitusTech/winutil/blob/main/winutil.ps1
    LogWrite "Uninstalling Bloatware"
    $Bloatware = @(
        #Unnecessary Windows 10 AppX Apps
        "Microsoft.3DBuilder"
        "Microsoft.Microsoft3DViewer"
        "Microsoft.AppConnector"
        "Microsoft.BingFinance"
        "Microsoft.BingNews"
        "Microsoft.BingSports"
        "Microsoft.BingTranslator"
        "Microsoft.BingWeather"
        "Microsoft.BingFoodAndDrink"
        "Microsoft.BingHealthAndFitness"
        "Microsoft.BingTravel"
        "Microsoft.MinecraftUWP"
        "Microsoft.GamingServices"
        "Microsoft.WindowsReadingList"
        "Microsoft.GetHelp"
        "Microsoft.Getstarted"
        "Microsoft.Messaging"
        "Microsoft.Microsoft3DViewer"
        "Microsoft.MicrosoftSolitaireCollection"
        "Microsoft.NetworkSpeedTest"
        "Microsoft.News"
        "Microsoft.Office.Lens"
        "Microsoft.Office.Sway"
        "Microsoft.Office.OneNote"
        "Microsoft.OneConnect"
        "Microsoft.People"
        "Microsoft.Print3D"
        "Microsoft.SkypeApp"
        "Microsoft.Wallet"
        "Microsoft.Whiteboard"
        "Microsoft.WindowsAlarms"
        "microsoft.windowscommunicationsapps"
        "Microsoft.WindowsFeedbackHub"
        "Microsoft.WindowsMaps"
        "Microsoft.WindowsPhone"
        "Microsoft.WindowsSoundRecorder"
        "Microsoft.XboxApp"
        "Microsoft.ConnectivityStore"
        "Microsoft.CommsPhone"
        "Microsoft.ScreenSketch"
        "Microsoft.Xbox.TCUI"
        "Microsoft.XboxGameOverlay"
        "Microsoft.XboxGamingOverlay"
        "Microsoft.XboxGameCallableUI"
        "Microsoft.XboxSpeechToTextOverlay"
        "Microsoft.MixedReality.Portal"
        "Microsoft.XboxIdentityProvider"
        "*Xbox*"
        "Microsoft.ZuneMusic"
        "Microsoft.ZuneVideo"
        "Microsoft.YourPhone"
        "Microsoft.Getstarted"
        "Microsoft.MicrosoftOfficeHub"

        #Sponsored Windows 10 AppX Apps
        #Add sponsored/featured apps to remove in the "*AppName*" format
        "*EclipseManager*"
        "*ActiproSoftwareLLC*"
        "*AdobeSystemsIncorporated.AdobePhotoshopExpress*"
        "*Duolingo-LearnLanguagesforFree*"
        "*PandoraMediaInc*"
        "*CandyCrush*"
        "*BubbleWitch3Saga*"
        "*Wunderlist*"
        "*Flipboard*"
        "*Twitter*"
        "*Facebook*"
        "*Royal Revolt*"
        "*Sway*"
        "*Speed Test*"
        "*Dolby*"
        "*Viber*"
        "*ACGMediaPlayer*"
        "*Netflix*"
        "*OneCalendar*"
        "*LinkedInforWindows*"
        "*HiddenCityMysteryofShadows*"
        "*Hulu*"
        "*HiddenCity*"
        "*AdobePhotoshopExpress*"
        "*HotspotShieldFreeVPN*"
        "*MicrosoftTeams*"


        #Optional: Typically not removed but you can if you need to
        "*Microsoft.Advertising.Xaml*"
        #"*Microsoft.MSPaint*"
        #"*Microsoft.MicrosoftStickyNotes*"
        #"*Microsoft.Windows.Photos*"
        #"*Microsoft.WindowsCalculator*"
        #"*Microsoft.WindowsStore*"

        # W11 Widgets 
        # https://pureinfotech.com/uninstall-widgets-powershell-windows-11/
        "*WebExperience*"


        # bloatware apps from BloatyNosy
        "*2FE3CB00.PICSART-PHOTOSTUDIO*"
        "*4DF9E0F8.Netflix*"
        "*5319275A.WhatsAppDesktop*"
        "*9E2F88E3.TWITTER*"
        "*NAVER.LINEwin8_8ptj331gd3tyt*"
        "*SpotifyAB.SpotifyMusic*"
        "*king.com.CandyCrushFriends*"
        "*king.com.CandyCrushSaga*"
        "*king.com.FarmHeroesSaga*"
        "*22364Disney.ESPNBetaPWA*"
        "*5A894077.McAfeeSecurity*"
        "*AdobeSystemsIncorporated.AdobeCreativeCloudExpress*"
        "*AmazonVideo.PrimeVideo*"
        "*AppUp.IntelGraphicsExperience*"
        "*B9ECED6F.ASUSPCAssistant*"
        "*B9ECED6F.ScreenPadMaster*"
        "*BytedancePte.Ltd.TikTok*"
        "*Clipchamp.Clipchamp*"
        "*DTSInc.DTSAudioProcess*"
        "*AdobeSystemsIncorporated.AdobeLightroom&"
        "*AdobeSystemsIncorporated.AdobePhotoshopExpress*"
        "*Clipchamp.Clipchamp_yxz26nhyzhsrt*"
        "*CorelCorporation.PaintShopPro*"
        "*FACEBOOK.317180B0BB486*"
        "*Facebook.InstagramBeta*"
        "*AD2F1837.HPJumpStarts*"
        "*AD2F1837.HPPCHardwareDiagnosticsWindows*"
        "*AD2F1837.HPPowerManager*"
        "*AD2F1837.HPPrivacySettings*"
        "*AD2F1837.HPSupportAssistant*"
        "*AD2F1837.HPSureShieldAI*"
        "*AD2F1837.HPSystemInformation*"
        "*AD2F1837.HPQuickDrop*"
        "*AD2F1837.HPWorkWell*"
        "*AD2F1837.myHP*"
        "*AD2F1837.HPDesktopSupportUtilities*"
        "*AD2F1837.HPQuickTouch*"
        "*AD2F1837.HPEasyClean*"
        "*AD2F1837.HPSystemInformation*"
        "*Microsoft.549981C3F5F10*"
        "*Microsoft.BingNews*"
        "*Microsoft.BingWeather*"
        "*Microsoft.GamingApp*"
        "*Microsoft.Getstarted*"
        "*Microsoft.Microsoft3DViewer*"
        "*Microsoft.MicrosoftOfficeHub*"
        "*Microsoft.MicrosoftSolitaireCollection*"
        "*Microsoft.MicrosoftStickyNotes*"
        "*Microsoft.MixedReality.Portal*"
        "*Microsoft.Office.OneNote*"
        "*Microsoft.OneDriveSync*"
        "*Microsoft.OneConnect*"
        "*Microsoft.People*"
        "*Microsoft.Print3D*"
        "*Microsoft.SkypeApp*"
        "*Microsoft.Wallet*"
        "*Microsoft.WindowsSoundRecorder*"

        )

foreach ($Bloat in $Bloatware) {
    Get-AppxPackage -Name $Bloat| Remove-AppxPackage
    Get-AppxProvisionedPackage -Online | Where-Object DisplayName -like $Bloat | Remove-AppxProvisionedPackage -Online
    LogWrite "Trying to remove $Bloat."
}

# Set Services to Manual
# pulled from Titus WinUtil
# https://github.com/ChrisTitusTech/winutil/blob/main/winutil.ps1
$services = @(
    "ALG"                                          # Application Layer Gateway Service(Provides support for 3rd party protocol plug-ins for Internet Connection Sharing)
    "AJRouter"                                     # Needed for AllJoyn Router Service
    "BcastDVRUserService_48486de"                  # GameDVR and Broadcast is used for Game Recordings and Live Broadcasts
    #"BDESVC"                                      # Bitlocker Drive Encryption Service
    #"BFE"                                         # Base Filtering Engine (Manages Firewall and Internet Protocol security)
    #"BluetoothUserService_48486de"                # Bluetooth user service supports proper functionality of Bluetooth features relevant to each user session.
    #"BrokerInfrastructure"                        # Windows Infrastructure Service (Controls which background tasks can run on the system)
    "Browser"                                      # Let users browse and locate shared resources in neighboring computers
    # "BthAvctpSvc"                                  # AVCTP service (needed for Bluetooth Audio Devices or Wireless Headphones)
    "CaptureService_48486de"                       # Optional screen capture functionality for applications that call the Windows.Graphics.Capture API.
    # "cbdhsvc_48486de"                              # Clipboard Service
    "diagnosticshub.standardcollector.service"     # Microsoft (R) Diagnostics Hub Standard Collector Service
    "DiagTrack"                                    # Diagnostics Tracking Service
    "dmwappushservice"                             # WAP Push Message Routing Service
    "DPS"                                          # Diagnostic Policy Service (Detects and Troubleshoots Potential Problems)
    "edgeupdate"                                   # Edge Update Service
    "edgeupdatem"                                  # Another Update Service
    "EntAppSvc"                                    # Enterprise Application Management.
    "Fax"                                          # Fax Service
    "fhsvc"                                        # Fax History
    "FontCache"                                    # Windows font cache
    #"FrameServer"                                 # Windows Camera Frame Server (Allows multiple clients to access video frames from camera devices)
    "gupdate"                                      # Google Update
    "gupdatem"                                     # Another Google Update Service
    "iphlpsvc"                                     # ipv6(Most websites use ipv4 instead)
    "lfsvc"                                        # Geolocation Service
    #"LicenseManager"                              # Disable LicenseManager (Windows Store may not work properly)
    # "lmhosts"                                      # TCP/IP NetBIOS Helper
    "MapsBroker"                                   # Downloaded Maps Manager
    "MicrosoftEdgeElevationService"                # Another Edge Update Service
    "MSDTC"                                        # Distributed Transaction Coordinator
    "ndu"                                          # Windows Network Data Usage Monitor (Disabling Breaks Task Manager Per-Process Network Monitoring)
    "NetTcpPortSharing"                            # Net.Tcp Port Sharing Service
    "PcaSvc"                                       # Program Compatibility Assistant Service
    "PerfHost"                                     # Remote users and 64-bit processes to query performance.
    "PhoneSvc"                                     # Phone Service(Manages the telephony state on the device)
    #"PNRPsvc"                                     # Peer Name Resolution Protocol (Some peer-to-peer and collaborative applications, such as Remote Assistance, may not function, Discord will still work)
    #"p2psvc"                                      # Peer Name Resolution Protocol(Enables multi-party communication using Peer-to-Peer Grouping.  If disabled, some applications, such as HomeGroup, may not function. Discord will still work)iscord will still work)
    #"p2pimsvc"                                    # Peer Networking Identity Manager (Peer-to-Peer Grouping services may not function, and some applications, such as HomeGroup and Remote Assistance, may not function correctly. Discord will still work)
    # "PrintNotify"                                  # Windows printer notifications and extentions
    # "QWAVE"                                        # Quality Windows Audio Video Experience (audio and video might sound worse)
    # "RemoteAccess"                                 # Routing and Remote Access
    "RemoteRegistry"                               # Remote Registry
    "RetailDemo"                                   # Demo Mode for Store Display
    # "RtkBtManServ"                                 # Realtek Bluetooth Device Manager Service
    "SCardSvr"                                     # Windows Smart Card Service
    # "seclogon"                                     # Secondary Logon (Disables other credentials only password will work)
    "SEMgrSvc"                                     # Payments and NFC/SE Manager (Manages payments and Near Field Communication (NFC) based secure elements)
    "SharedAccess"                                 # Internet Connection Sharing (ICS)
    # "Spooler"                                     # Printing
    "stisvc"                                       # Windows Image Acquisition (WIA)
    #"StorSvc"                                     # StorSvc (usb external hard drive will not be reconized by windows)
    "SysMain"                                      # Analyses System Usage and Improves Performance
    "TrkWks"                                       # Distributed Link Tracking Client
    #"WbioSrvc"                                    # Windows Biometric Service (required for Fingerprint reader / facial detection)
    "WerSvc"                                       # Windows error reporting
    "wisvc"                                        # Windows Insider program(Windows Insider will not work if Disabled)
    #"WlanSvc"                                     # WLAN AutoConfig
    "WMPNetworkSvc"                                # Windows Media Player Network Sharing Service
    "WpcMonSvc"                                    # Parental Controls
    "WPDBusEnum"                                   # Portable Device Enumerator Service
    "WpnService"                                   # WpnService (Push Notifications may not work)
    #"wscsvc"                                      # Windows Security Center Service
    "WSearch"                                      # Windows Search
    "XblAuthManager"                               # Xbox Live Auth Manager (Disabling Breaks Xbox Live Games)
    "XblGameSave"                                  # Xbox Live Game Save Service (Disabling Breaks Xbox Live Games)
    "XboxNetApiSvc"                                # Xbox Live Networking Service (Disabling Breaks Xbox Live Games)
    "XboxGipSvc"                                   # Xbox Accessory Management Service
    # Hp services
    "HPAppHelperCap"
    "HPDiagsCap"
    "HPNetworkCap"
    "HPSysInfoCap"
    "HpTouchpointAnalyticsService"
    # Hyper-V services
    "HvHost"
    "vmicguestinterface"
    "vmicheartbeat"
    "vmickvpexchange"
    "vmicrdv"
    "vmicshutdown"
    "vmictimesync"
    "vmicvmsession"
    # Services that cannot be disabled
    #"WdNisSvc"
    )

foreach ($service in $services) {
    # -ErrorAction SilentlyContinue is so it doesn't write an error to stdout if a service doesn't exist

    LogWrite "Setting $service StartupType to Manual"
    Get-Service -Name $service -ErrorAction SilentlyContinue | Set-Service -StartupType Manual
}

} # END OF DEBLOAT



if($Argument -like '*Restart*') {

    if($Argument -like '*RestartInstant*') {
        shutdown /r /t 0
        exit
    }
    else {

        LogWrite "Restarting PC in 30 seconds"
        powershell Start-Sleep -s 30

        shutdown /r /t 0
    }
}










Write-Host "Finished!"

Exit