<%@ 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: downloads universal PrinterInstaller.exe
' 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, ma.alias, ma.machinenumber " & _
             "FROM printers p " & _
             "LEFT JOIN models m ON p.modelid = m.modelnumberid " & _
             "LEFT JOIN vendors v ON m.vendorid = v.vendorid " & _
             "LEFT JOIN machines ma ON p.machineid = ma.machineid " & _
             "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, ma.alias, ma.machinenumber " & _
             "FROM printers p " & _
             "LEFT JOIN models m ON p.modelid = m.modelnumberid " & _
             "LEFT JOIN vendors v ON m.vendorid = v.vendorid " & _
             "LEFT JOIN machines ma ON p.machineid = ma.machineid " & _
             "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 printer name to use
        ' Prefer Windows Name from database if it's already in standardized format (contains dashes)
        ' Otherwise generate standardized name (same logic as api_printers.asp)
        Dim machineAlias, machineNumber, machineName, cleanMachine, cleanModel, shortDescription, standardName

        ' Check if printerwindowsname is already standardized (contains dashes, not just spaces)
        If InStr(printerInfo("name"), "-") > 0 Then
            ' Use database Windows Name as-is (user manually set it)
            standardName = printerInfo("name")
        Else
            ' Generate standardized name
            machineAlias = rs("alias") & ""
            machineNumber = rs("machinenumber") & ""
            If machineAlias <> "" Then
                machineName = machineAlias
            Else
                machineName = machineNumber
            End If

            cleanMachine = Replace(machineName, " ", "")
            cleanMachine = Replace(cleanMachine, "Machine", "")
            cleanModel = Replace(printerInfo("model"), " ", "")

            ' Extract short description from model number
            If InStr(cleanModel, "ColorLaserJet") > 0 Then
                shortDescription = "ColorLaserJet"
            ElseIf InStr(cleanModel, "LaserJetPro") > 0 Then
                shortDescription = "LaserJetPro"
            ElseIf InStr(cleanModel, "LaserJet") > 0 Then
                shortDescription = "LaserJet"
            ElseIf InStr(cleanModel, "Altalink") > 0 Then
                shortDescription = "Altalink"
            ElseIf InStr(cleanModel, "Versalink") > 0 Then
                shortDescription = "Versalink"
            ElseIf InStr(cleanModel, "DesignJet") > 0 Then
                shortDescription = "DesignJet"
            ElseIf InStr(cleanModel, "DTC") > 0 Then
                shortDescription = "DTC"
            Else
                Dim j, char2
                shortDescription = ""
                For j = 1 To Len(cleanModel)
                    char2 = Mid(cleanModel, j, 1)
                    If char2 >= "0" And char2 <= "9" Then
                        Exit For
                    End If
                    shortDescription = shortDescription & char2
                Next
                If shortDescription = "" Then
                    shortDescription = cleanModel
                End If
            End If

            ' Build standard name: CSFName-Location-VendorModel
            If printerInfo("csfname") <> "" And printerInfo("csfname") <> "NONE" And printerInfo("csfname") <> "gage lab " Then
                If cleanMachine <> "" And LCase(printerInfo("csfname")) <> LCase(cleanMachine) Then
                    standardName = printerInfo("csfname") & "-" & cleanMachine & "-" & printerInfo("vendor") & shortDescription
                Else
                    standardName = printerInfo("csfname") & "-" & printerInfo("vendor") & shortDescription
                End If
            Else
                If cleanMachine <> "" Then
                    standardName = cleanMachine & "-" & printerInfo("vendor") & shortDescription
                Else
                    standardName = "Printer" & rs("printerid") & "-" & printerInfo("vendor") & shortDescription
                End If
            End If
        End If

        printerInfo("standardname") = standardName

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

        printers.Add CStr(rs("printerid")), 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)

    ' Separate printers into two groups:
    ' 1. Those with specific installers (run individually with /SILENT)
    ' 2. Those using universal installer (batch into one call)
    Dim printerKey, printer
    Dim specificInstallers, universalPrinters, universalNames
    Set specificInstallers = Server.CreateObject("Scripting.Dictionary")
    Set universalPrinters = Server.CreateObject("Scripting.Dictionary")
    universalNames = ""

    For Each printerKey In printers.Keys
        Set printer = printers(printerKey)
        If printer("installpath") <> "" Then
            specificInstallers.Add printerKey, printer
        Else
            universalPrinters.Add printerKey, printer
            If universalNames <> "" Then universalNames = universalNames & ","
            universalNames = universalNames & printer("standardname")
        End If
    Next

    ' Process printers with specific installers first (silent mode)
    For Each printerKey In specificInstallers.Keys
        Set printer = specificInstallers(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)

        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)
        Response.Write("echo." & vbCrLf)
    Next

    ' Process universal installer printers (single call with all printer names)
    If universalPrinters.Count > 0 Then
        Response.Write("" & vbCrLf)
        Response.Write("echo ----------------------------------------" & vbCrLf)
        Response.Write("echo Installing " & universalPrinters.Count & " printer(s) via Universal Installer:" & vbCrLf)

        For Each printerKey In universalPrinters.Keys
            Set printer = universalPrinters(printerKey)
            Response.Write("echo   - " & printer("name") & vbCrLf)
        Next

        Response.Write("echo ----------------------------------------" & vbCrLf)
        Response.Write("echo." & vbCrLf)
        Response.Write("echo Downloading PrinterInstaller.exe..." & vbCrLf)
        Response.Write("powershell -NoProfile -Command """ & _
                      "$ProgressPreference = 'SilentlyContinue'; " & _
                      "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; " & _
                      "Invoke-WebRequest -Uri 'https://tsgwp00525.rd.ds.ge.com/shopdb/installers/PrinterInstaller.exe' " & _
                      "-OutFile '%TEMP%\PrinterInstaller.exe' -UseBasicParsing -UseDefaultCredentials""" & vbCrLf)
        Response.Write("if exist ""%TEMP%\PrinterInstaller.exe"" (" & vbCrLf)
        Response.Write("    echo Running installer..." & vbCrLf)
        Response.Write("    ""%TEMP%\PrinterInstaller.exe"" ""/PRINTER=" & universalNames & """" & vbCrLf)
        Response.Write("    del ""%TEMP%\PrinterInstaller.exe"" 2>nul" & vbCrLf)
        Response.Write(") else (" & vbCrLf)
        Response.Write("    echo ERROR: Could not download PrinterInstaller.exe" & vbCrLf)
        Response.Write(")" & vbCrLf)
        Response.Write("echo." & vbCrLf)
    End If

    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
%>
