@echo off
setlocal EnableExtensions
cls

REM ============================================================
REM   THP - DEVICE CHECK-IN
REM   Generated by checkin.thp-ky.org - do not edit.
REM   Runs as a standard user. No admin rights required.
REM ============================================================

set "CHECKIN_URL=https://checkin.thp-ky.org/submit"
set "CHECKIN_CODE=THP-11B08DE7A7"
set "CHECKIN_ORG=THP"
set "CHECKIN_AGENT=1.0.0"
set "CHECKIN_ASSET="
set "CHECKIN_CONTACT="

cd /d "%SystemRoot%"
title THP Device Check-In

echo.
echo  ============================================================
echo    THP - DEVICE CHECK-IN
echo  ============================================================
echo.
echo    This reads your computer's make, model and serial number
echo    and sends them to the IT inventory over a secure
echo    connection. Nothing on your computer is changed.
echo.
echo  ------------------------------------------------------------

findstr /b /c:":::" "%~f0" | powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command "$global:CheckInExit=1; $body=@($input | ForEach-Object { $_.Substring(3) }) -join [Environment]::NewLine; & ([scriptblock]::Create($body)) | Out-Null; exit ([int]$global:CheckInExit)"

set "RC=%ERRORLEVEL%"
echo  ------------------------------------------------------------
echo.

if "%RC%"=="0" goto :ok
goto :failed

:ok
echo    CHECK-IN COMPLETE. Thank you - your computer has been
echo    recorded. This window will close by itself.
echo.
timeout /t 8 /nobreak >nul 2>&1 || ping -n 9 127.0.0.1 >nul 2>&1
endlocal
exit /b 0

:failed
echo    CHECK-IN FAILED - nothing was recorded.
echo.
echo    Check that you have an internet connection and try again.
echo    If it keeps failing, send IT a screenshot of this window.
echo.
pause
endlocal
exit /b 1

:::$ErrorActionPreference = 'Stop'
:::
:::function Field($k, $v) {
:::    Write-Host ('   {0,-17}: ' -f $k) -NoNewline -ForegroundColor DarkGray
:::    Write-Host $v -ForegroundColor White
:::}
:::function Info($m) { Write-Host ('   ' + $m) -ForegroundColor Cyan }
:::function Good($m) { Write-Host ('   ' + $m) -ForegroundColor Green }
:::function Problem($m) { Write-Host ('   ' + $m) -ForegroundColor Red }
:::
:::Write-Host ''
:::Info 'Reading system information...'
:::
:::try {
:::    $cs   = Get-CimInstance -ClassName Win32_ComputerSystem
:::    $bios = Get-CimInstance -ClassName Win32_BIOS
:::    $csp  = Get-CimInstance -ClassName Win32_ComputerSystemProduct
:::    $os   = Get-CimInstance -ClassName Win32_OperatingSystem
:::} catch {
:::    Problem ('Could not read system information: ' + $_.Exception.Message)
:::    return
:::}
:::
:::$make = ''
:::if ($cs.Manufacturer) { $make = $cs.Manufacturer.Trim() }
:::$model = ''
:::if ($cs.Model) { $model = $cs.Model.Trim() }
:::if ($make -match 'LENOVO' -and $csp.Version) {
:::    $friendly = $csp.Version.Trim()
:::    if ($friendly -and $friendly -ne $model) { $model = ('{0} ({1})' -f $friendly, $model) }
:::}
:::
:::$serial = ''
:::if ($bios.SerialNumber) { $serial = $bios.SerialNumber.Trim() }
:::if ($serial -eq '' -or $serial -match '^(to be filled|system serial|default string|none|not applicable|not specified)' -or $serial -match '^0+$') {
:::    if ($csp.IdentifyingNumber) { $serial = $csp.IdentifyingNumber.Trim() }
:::}
:::
:::$consoleUser = ''
:::if ($cs.UserName) { $consoleUser = $cs.UserName }
:::if (-not $consoleUser) { $consoleUser = $env:USERDOMAIN + '\' + $env:USERNAME }
:::$runAs = $env:USERDOMAIN + '\' + $env:USERNAME
:::
:::$osName = $os.Caption
:::$osVersionLabel = ''
:::$ubr = ''
:::try {
:::    $cv = Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -ErrorAction Stop
:::    if ($cv.DisplayVersion) { $osVersionLabel = $cv.DisplayVersion }
:::    elseif ($cv.ReleaseId) { $osVersionLabel = $cv.ReleaseId }
:::    if ($null -ne $cv.UBR) { $ubr = [string]$cv.UBR }
:::} catch { }
:::$osBuild = [string]$os.BuildNumber
:::if ($ubr -ne '') { $osBuild = ('{0}.{1}' -f $os.BuildNumber, $ubr) }
:::
:::$ip = ''
:::$mac = ''
:::$nicName = ''
:::try {
:::    $cfg = Get-NetIPConfiguration -ErrorAction Stop | Where-Object { $_.IPv4DefaultGateway -and $_.NetAdapter.Status -eq 'Up' } | Select-Object -First 1
:::    if ($cfg) {
:::        $ip = ($cfg.IPv4Address | Select-Object -First 1).IPAddress
:::        $mac = $cfg.NetAdapter.MacAddress
:::        $nicName = $cfg.InterfaceAlias
:::    }
:::} catch { }
:::if (-not $ip) {
:::    try {
:::        $nic = Get-CimInstance -ClassName Win32_NetworkAdapterConfiguration -Filter 'IPEnabled = True' | Where-Object { $_.DefaultIPGateway } | Select-Object -First 1
:::        if ($nic) {
:::            $ip = ($nic.IPAddress | Where-Object { $_ -notmatch ':' }) -join ';'
:::            $mac = $nic.MACAddress
:::            $nicName = $nic.Description
:::        }
:::    } catch { }
:::}
:::
:::$partOfDomain = [bool]$cs.PartOfDomain
:::if ($partOfDomain) { $domain = $cs.Domain } else { $domain = $cs.Workgroup }
:::
:::$biosDate = ''
:::if ($bios.ReleaseDate) {
:::    try { $biosDate = ([datetime]$bios.ReleaseDate).ToString('yyyy-MM-dd') } catch { }
:::}
:::$biosVer = ''
:::if ($bios.SMBIOSBIOSVersion) { $biosVer = $bios.SMBIOSBIOSVersion.Trim() }
:::$uuid = ''
:::if ($csp.UUID) { $uuid = $csp.UUID }
:::
:::Write-Host ''
:::Field 'Computer name' $env:COMPUTERNAME
:::Field 'Logged-in user' $consoleUser
:::Field 'Manufacturer' $make
:::Field 'Model' $model
:::Field 'Serial number' $serial
:::Field 'Operating system' (($osName, $osVersionLabel, ('build ' + $osBuild) | Where-Object { $_ }) -join '  ')
:::Field 'Domain' $domain
:::Field 'IP address' $ip
:::Field 'MAC address' $mac
:::Field 'BIOS' (($biosVer, $biosDate | Where-Object { $_ }) -join '  ')
:::Write-Host ''
:::
:::$payload = [ordered]@{
:::    enrollment_code = $env:CHECKIN_CODE
:::    agent_version   = $env:CHECKIN_AGENT
:::    computer_name   = $env:COMPUTERNAME
:::    logged_on_user  = $consoleUser
:::    script_run_as   = $runAs
:::    manufacturer    = $make
:::    model           = $model
:::    serial_number   = $serial
:::    system_uuid     = $uuid
:::    bios_version    = $biosVer
:::    bios_date       = $biosDate
:::    os_name         = $osName
:::    os_version      = $osVersionLabel
:::    os_build        = $osBuild
:::    domain          = $domain
:::    part_of_domain  = $partOfDomain
:::    ipv4_address    = $ip
:::    mac_address     = $mac
:::    network_adapter = $nicName
:::    asset_tag       = $env:CHECKIN_ASSET
:::    contact_name    = $env:CHECKIN_CONTACT
:::}
:::
:::$json = $payload | ConvertTo-Json -Depth 4 -Compress
:::$bytes = [System.Text.Encoding]::UTF8.GetBytes($json)
:::
:::Info ('Sending to ' + $env:CHECKIN_URL)
:::try {
:::    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
:::} catch { }
:::
:::try {
:::    $hdrs = @{ 'User-Agent' = ('Novo01-Checkin/' + $env:CHECKIN_AGENT) }
:::    $resp = Invoke-RestMethod -Uri $env:CHECKIN_URL -Method Post -Body $bytes -ContentType 'application/json' -TimeoutSec 30 -Headers $hdrs
:::    Good ('Received by ' + $env:CHECKIN_ORG + '. Reference #' + $resp.id)
:::    $global:CheckInExit = 0
:::} catch {
:::    $msg = $_.Exception.Message
:::    try {
:::        $r = $_.Exception.Response
:::        if ($r) {
:::            $sr = New-Object System.IO.StreamReader($r.GetResponseStream())
:::            $detail = $sr.ReadToEnd()
:::            if ($detail) { $msg = $msg + ' - ' + $detail }
:::        }
:::    } catch { }
:::    Problem ('Check-in could not be sent: ' + $msg)
:::    $global:CheckInExit = 1
:::}
