<%@ Language=VBScript %>
<!--#include file="./includes/sql.asp"-->
<%
' install_printer.asp
' Generates a batch file to install printer(s)
' - If printer has installpath: downloads and runs specific .exe
' - If no installpath: uses PowerShell to install with universal driver
' Usage: install_printer.asp?printer=GuardDesk-HIDDTC

Dim printerNames, printerIds, printerArray, i, fileName
printerNames = Request.QueryString("printer")
printerIds = Request.QueryString("printerid")

' Sanitize printer names
If printerNames <> "" Then
    printerNames = Replace(printerNames, """", "")
    printerNames = Replace(printerNames, "&", "")
    printerNames = Replace(printerNames, "|", "")
    printerNames = Replace(printerNames, "<", "")
    printerNames = Replace(printerNames, ">", "")
End If

' Query database for printer info
Dim strSQL, rs, printers
Set printers = Server.CreateObject("Scripting.Dictionary")

If printerIds <> "" Then
    ' Query by printer ID (preferred - handles printers with duplicate names)
    printerArray = Split(printerIds, ",")

    strSQL = "SELECT p.printerid, p.printerwindowsname, p.printercsfname, " & _
             "p.fqdn, p.ipaddress, p.installpath, " & _
             "v.vendor, m.modelnumber " & _
             "FROM printers p " & _
             "LEFT JOIN models m ON p.modelid = m.modelnumberid " & _
             "LEFT JOIN vendors v ON m.vendorid = v.vendorid " & _
             "WHERE p.printerid IN ("

    For i = 0 To UBound(printerArray)
        If i > 0 Then strSQL = strSQL & ","
        strSQL = strSQL & CLng(Trim(printerArray(i)))
    Next
    strSQL = strSQL & ")"

ElseIf printerNames <> "" Then
    ' Query by printer name (legacy support)
    printerArray = Split(printerNames, ",")

    strSQL = "SELECT p.printerid, p.printerwindowsname, p.printercsfname, " & _
             "p.fqdn, p.ipaddress, p.installpath, " & _
             "v.vendor, m.modelnumber " & _
             "FROM printers p " & _
             "LEFT JOIN models m ON p.modelid = m.modelnumberid " & _
             "LEFT JOIN vendors v ON m.vendorid = v.vendorid " & _
             "WHERE p.printerwindowsname IN ("

    For i = 0 To UBound(printerArray)
        If i > 0 Then strSQL = strSQL & ","
        strSQL = strSQL & "'" & Replace(Trim(printerArray(i)), "'", "''") & "'"
    Next
    strSQL = strSQL & ")"
End If

If printerIds <> "" Or printerNames <> "" Then

    Set rs = objConn.Execute(strSQL)

    While Not rs.EOF
        Dim printerInfo
        Set printerInfo = Server.CreateObject("Scripting.Dictionary")
        printerInfo("name") = rs("printerwindowsname") & ""
        printerInfo("csfname") = rs("printercsfname") & ""
        printerInfo("fqdn") = rs("fqdn") & ""
        printerInfo("ipaddress") = rs("ipaddress") & ""
        printerInfo("installpath") = rs("installpath") & ""
        printerInfo("vendor") = rs("vendor") & ""
        printerInfo("model") = rs("modelnumber") & ""

        ' Determine preferred address
        If printerInfo("fqdn") <> "" And printerInfo("fqdn") <> "USB" Then
            printerInfo("address") = printerInfo("fqdn")
        Else
            printerInfo("address") = printerInfo("ipaddress")
        End If

        printers.Add rs("printerwindowsname"), printerInfo
        rs.MoveNext
    Wend

    rs.Close
    Set rs = Nothing
End If

' Generate filename
If printers.Count = 0 Then
    fileName = "Install_Printers.bat"
ElseIf printers.Count = 1 Then
    fileName = "Install_" & printers.Items()(0)("name") & ".bat"
Else
    fileName = "Install_" & printers.Count & "_Printers.bat"
End If

' Set headers
Response.ContentType = "application/bat"
Response.AddHeader "Content-Type", "application/octet-stream"
Response.AddHeader "Content-Disposition", "attachment; filename=" & fileName

' Generate batch file
Response.Write("@echo off" & vbCrLf)
Response.Write("setlocal enabledelayedexpansion" & vbCrLf)
Response.Write("" & vbCrLf)
Response.Write("echo ========================================" & vbCrLf)
Response.Write("echo  GE Aerospace Printer Installer" & vbCrLf)
Response.Write("echo ========================================" & vbCrLf)
Response.Write("echo." & vbCrLf)

If printers.Count = 0 Then
    Response.Write("echo No printers specified" & vbCrLf)
    Response.Write("pause" & vbCrLf)
    Response.Write("exit /b 1" & vbCrLf)
Else
    Response.Write("echo Installing " & printers.Count & " printer(s)..." & vbCrLf)
    Response.Write("echo." & vbCrLf)

    ' Process each printer
    Dim printerKey, printer
    For Each printerKey In printers.Keys
        Set printer = printers(printerKey)

        Response.Write("" & vbCrLf)
        Response.Write("echo ----------------------------------------" & vbCrLf)
        Response.Write("echo Installing: " & printer("name") & vbCrLf)

        If printer("csfname") <> "" Then
            Response.Write("echo CSF Name: " & printer("csfname") & vbCrLf)
        End If

        Response.Write("echo Model: " & printer("model") & vbCrLf)
        Response.Write("echo Address: " & printer("address") & vbCrLf)
        Response.Write("echo ----------------------------------------" & vbCrLf)
        Response.Write("echo." & vbCrLf)

        If printer("installpath") <> "" Then
            ' Has specific installer - download and run it
            Response.Write("echo Downloading specific installer..." & vbCrLf)
            Response.Write("powershell -NoProfile -Command """ & _
                          "$ProgressPreference = 'SilentlyContinue'; " & _
                          "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; " & _
                          "Invoke-WebRequest -Uri 'https://tsgwp00525.rd.ds.ge.com/shopdb/" & printer("installpath") & "' " & _
                          "-OutFile '%TEMP%\printer_installer.exe' -UseBasicParsing -UseDefaultCredentials""" & vbCrLf)
            Response.Write("if exist ""%TEMP%\printer_installer.exe"" (" & vbCrLf)
            Response.Write("    echo Running installer..." & vbCrLf)
            Response.Write("    ""%TEMP%\printer_installer.exe"" /SILENT" & vbCrLf)
            Response.Write("    del ""%TEMP%\printer_installer.exe"" 2>nul" & vbCrLf)
            Response.Write(") else (" & vbCrLf)
            Response.Write("    echo ERROR: Could not download installer" & vbCrLf)
            Response.Write(")" & vbCrLf)
        Else
            ' No installer - use universal driver
            Dim driverName, driverInf

            Select Case UCase(printer("vendor"))
                Case "HP"
                    driverName = "HP Universal Printing PCL 6"
                    driverInf = "hpcu255u.inf"
                Case "XEROX"
                    driverName = "Xerox Global Print Driver PCL6"
                    driverInf = "xeroxgpd.inf"
                Case "HID"
                    driverName = "HP Universal Printing PCL 6"
                    driverInf = "hpcu255u.inf"
                Case Else
                    driverName = "Generic / Text Only"
                    driverInf = ""
            End Select

            Response.Write("echo Using universal driver: " & driverName & vbCrLf)
            Response.Write("echo." & vbCrLf)

            ' Generate PowerShell script to install printer
            Response.Write("powershell -NoProfile -ExecutionPolicy Bypass -Command """ & vbCrLf)
            Response.Write("    Write-Host 'Installing printer with universal driver...' -ForegroundColor Cyan;" & vbCrLf)
            Response.Write("    " & vbCrLf)
            Response.Write("    $printerName = '" & Replace(printer("name"), "'", "''") & "';" & vbCrLf)
            Response.Write("    $address = '" & Replace(printer("address"), "'", "''") & "';" & vbCrLf)
            Response.Write("    $driverName = '" & Replace(driverName, "'", "''") & "';" & vbCrLf)
            Response.Write("    $portName = 'IP_' + $address;" & vbCrLf)
            Response.Write("    " & vbCrLf)

            ' Check if driver is installed
            If driverInf <> "" Then
                Response.Write("    # Check if driver exists" & vbCrLf)
                Response.Write("    $driver = Get-PrinterDriver -Name $driverName -ErrorAction SilentlyContinue;" & vbCrLf)
                Response.Write("    if (-not $driver) {" & vbCrLf)
                Response.Write("        Write-Host 'ERROR: Universal driver not found!' -ForegroundColor Red;" & vbCrLf)
                Response.Write("        Write-Host 'Please install ' $driverName ' from Windows Update or driver package' -ForegroundColor Yellow;" & vbCrLf)
                Response.Write("        exit 1;" & vbCrLf)
                Response.Write("    }" & vbCrLf)
                Response.Write("    " & vbCrLf)
            End If

            ' Create port
            Response.Write("    # Create TCP/IP port" & vbCrLf)
            Response.Write("    $port = Get-PrinterPort -Name $portName -ErrorAction SilentlyContinue;" & vbCrLf)
            Response.Write("    if (-not $port) {" & vbCrLf)
            Response.Write("        Write-Host 'Creating printer port...' -ForegroundColor Yellow;" & vbCrLf)
            Response.Write("        Add-PrinterPort -Name $portName -PrinterHostAddress $address -ErrorAction Stop;" & vbCrLf)
            Response.Write("        Write-Host 'Port created successfully' -ForegroundColor Green;" & vbCrLf)
            Response.Write("    } else {" & vbCrLf)
            Response.Write("        Write-Host 'Port already exists' -ForegroundColor Green;" & vbCrLf)
            Response.Write("    }" & vbCrLf)
            Response.Write("    " & vbCrLf)

            ' Add printer
            Response.Write("    # Add printer" & vbCrLf)
            Response.Write("    $existingPrinter = Get-Printer -Name $printerName -ErrorAction SilentlyContinue;" & vbCrLf)
            Response.Write("    if (-not $existingPrinter) {" & vbCrLf)
            Response.Write("        Write-Host 'Adding printer...' -ForegroundColor Yellow;" & vbCrLf)
            Response.Write("        Add-Printer -Name $printerName -DriverName $driverName -PortName $portName -ErrorAction Stop;" & vbCrLf)
            Response.Write("        Write-Host 'Printer installed successfully!' -ForegroundColor Green;" & vbCrLf)
            Response.Write("    } else {" & vbCrLf)
            Response.Write("        Write-Host 'Printer already exists' -ForegroundColor Green;" & vbCrLf)
            Response.Write("    }" & vbCrLf)
            Response.Write("""" & vbCrLf)
            Response.Write("" & vbCrLf)
            Response.Write("if %ERRORLEVEL% neq 0 (" & vbCrLf)
            Response.Write("    echo ERROR: Failed to install printer" & vbCrLf)
            Response.Write(")" & vbCrLf)
        End If

        Response.Write("echo." & vbCrLf)
    Next

    Response.Write("" & vbCrLf)
    Response.Write("echo ========================================" & vbCrLf)
    Response.Write("echo Installation Complete!" & vbCrLf)
    Response.Write("echo ========================================" & vbCrLf)
    Response.Write("echo." & vbCrLf)
    Response.Write("pause" & vbCrLf)
End If

Response.Write("" & vbCrLf)
Response.Write(":: Self-delete this batch file" & vbCrLf)
Response.Write("(goto) 2>nul & del ""%~f0""" & vbCrLf)

' Cleanup
objConn.Close
Set objConn = Nothing
%>
