@echo off
setlocal
rem ============================================================================
rem  Hasaki - Bo cai in tem ma vach  -  v1.2 2026-08-06
rem  v1.2: driver Seagull (TSC/Honeywell) KHONG doc form he thong Windows ->
rem        them buoc NAP KHO GIAY CHUAN vao driver bang printui /Sr tu file
rem        mau xuat o may chuan (kem Print Method Thermal Transfer + Darkness
rem        dung). Tai file mau tu barcode.hasaki.vn, loi thi tu chuyen
rem        barcode1.hasaki.vn. Form he thong van tao (du phong may in khac).
rem  v1.1: sua loi 1804 (PS ep $null -> chuoi rong) - don Win32 vao C# helper.
rem  Tu dong lam (can quyen Administrator - bam Yes khi Windows hoi):
rem    1. Nap kho giay chuan vao driver may in tem (Hasaki 88x10 + Hasaki 105x22)
rem    2. Tao kho giay he thong (du phong cho may in khong dung driver Seagull)
rem    3. Tat "Dau trang va chan trang" khi in cho Chrome + Edge (chinh sach may)
rem  LUU Y: buoc 1 se THAY danh sach Stock cua driver may in tem bang bo chuan
rem         (kem Media Settings dung) - stock tu tao truoc do se mat.
rem  Go bo: xoa 2 form trong Print server properties > Forms (Win+R: printui /s /t1);
rem         xoa gia tri PrintHeaderFooter trong
rem         HKLM\SOFTWARE\Policies\{Google\Chrome,Microsoft\Edge}
rem  Log: %TEMP%\hasaki-barcode-setup.log
rem ============================================================================

net session >nul 2>&1
if %errorlevel% neq 0 (
  echo Dang xin quyen Administrator... Bam Yes o hop thoai ke tiep.
  powershell -NoProfile -Command "Start-Process -FilePath '%~f0' -Verb RunAs"
  exit /b
)

echo.
echo === Hasaki - Cai dat in tem ma vach (v1.2) ===
echo.
powershell -NoProfile -ExecutionPolicy Bypass -Command "$s=[IO.File]::ReadAllText('%~f0'); $m='###'+'PSBEGIN'+'###'; $i=$s.LastIndexOf($m); Invoke-Expression $s.Substring($i+$m.Length)"
echo.
pause
exit /b

###PSBEGIN###
$ErrorActionPreference = 'Stop'
try { Start-Transcript -Path (Join-Path $env:TEMP 'hasaki-barcode-setup.log') -Force | Out-Null } catch {}

$printers = @(Get-Printer)
if ($printers.Count -eq 0) { throw 'May nay chua co bat ky may in nao - cai driver may in truoc roi chay lai file nay.' }
$target = $printers | Where-Object { $_.Name -match 'TSC|PE200|PC42|Honeywell' } | Select-Object -First 1

Write-Host '--- Buoc 1/3: nap kho giay chuan vao driver may in tem ---'
# Driver Seagull (TSC/Honeywell) chi hien Stock RIENG cua no, khong doc form
# he thong -> nap thang bo Stock chuan (xuat tu may mau da in tot, kem
# Print Method = Thermal Transfer + Darkness dung) bang printui /Sr.
$datMap = @(
  @{ Pattern = 'PC42|Honeywell'; File = 'pc42t-hasaki.dat';     Ten = 'Honeywell PC42t' },
  @{ Pattern = 'TSC|PE200';      File = 'tsc-pe200-hasaki.dat'; Ten = 'TSC PE200' }
)
$hosts = @('https://barcode.hasaki.vn', 'https://barcode1.hasaki.vn')
try {
  [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
} catch {}
$imported = $false
foreach ($m in $datMap) {
  $prns = @($printers | Where-Object { $_.Name -match $m.Pattern })
  if ($prns.Count -eq 0) { continue }
  $tmp = Join-Path $env:TEMP $m.File
  $downloaded = $false
  foreach ($h in $hosts) {
    try {
      Invoke-WebRequest -Uri ($h + '/drv/' + $m.File) -OutFile $tmp -UseBasicParsing -TimeoutSec 30
      if ((Get-Item $tmp).Length -gt 1000) { $downloaded = $true; break }
    } catch { }
  }
  if (-not $downloaded) {
    Write-Host ("  [CHU Y] Chua tai duoc file mau cho {0} - kho giay se phai tao tay theo" -f $m.Ten)
    Write-Host  '          huong dan (barcode1.hasaki.vn/huong-dan.pdf, muc 2.1).'
    continue
  }
  foreach ($p in $prns) {
    $arg = 'printui.dll,PrintUIEntry /q /Sr /n "' + $p.Name + '" /a "' + $tmp + '" d u g'
    $proc = Start-Process -FilePath 'rundll32.exe' -ArgumentList $arg -Wait -PassThru -WindowStyle Hidden
    if ($proc.ExitCode -eq 0) {
      Write-Host ("  [OK] Da nap kho 'Hasaki 88x10' + 'Hasaki 105x22' vao may in '{0}'" -f $p.Name)
      Write-Host  '       (kem Print Method/Darkness chuan - stock tu tao cu bi thay the)'
      $imported = $true
    } else {
      Write-Host ("  [CHU Y] Nap kho vao '{0}' tra ma {1} - in thu de kiem tra;" -f $p.Name, $proc.ExitCode)
      Write-Host  '          khong duoc thi tao Stock tay theo huong dan muc 2.1.'
    }
  }
}
if (-not $target) {
  Write-Host '  [CHU Y] Chua thay may in TSC/Honeywell tren may nay - cai driver,'
  Write-Host '          cam may in roi chay lai file nay.'
} elseif (-not $imported) {
  Write-Host '  [CHU Y] Chua nap duoc kho chuan - van dung duoc bang cach tao Stock tay.'
}

Write-Host '--- Buoc 2/3: tao kho giay he thong (du phong may in khac) ---'
Add-Type -TypeDefinition @'
using System;
using System.Runtime.InteropServices;
public class HskForm {
  [StructLayout(LayoutKind.Sequential)] public struct SIZEL { public int cx; public int cy; }
  [StructLayout(LayoutKind.Sequential)] public struct RECTL { public int left; public int top; public int right; public int bottom; }
  [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
  public struct FORM_INFO_1 { public uint Flags; public string pName; public SIZEL Size; public RECTL ImageableArea; }
  [StructLayout(LayoutKind.Sequential)]
  public struct PRINTER_DEFAULTS { public IntPtr pDatatype; public IntPtr pDevMode; public uint DesiredAccess; }
  [DllImport("winspool.drv", SetLastError=true, CharSet=CharSet.Unicode)]
  static extern bool OpenPrinter(string pPrinterName, out IntPtr phPrinter, ref PRINTER_DEFAULTS pDefault);
  [DllImport("winspool.drv", SetLastError=true)]
  static extern bool ClosePrinter(IntPtr hPrinter);
  [DllImport("winspool.drv", SetLastError=true, CharSet=CharSet.Unicode)]
  static extern bool AddForm(IntPtr hPrinter, uint Level, ref FORM_INFO_1 pForm);
  [DllImport("winspool.drv", SetLastError=true, CharSet=CharSet.Unicode)]
  static extern bool DeleteForm(IntPtr hPrinter, string pFormName);
  public static string AddLabelForm(string printer, string name, double wmm, double hmm) {
    PRINTER_DEFAULTS pd = new PRINTER_DEFAULTS();
    pd.pDatatype = IntPtr.Zero;
    pd.pDevMode = IntPtr.Zero;
    pd.DesiredAccess = 0x000F000C;         // PRINTER_ALL_ACCESS
    IntPtr h;
    if (!OpenPrinter(printer, out h, ref pd)) {
      pd.DesiredAccess = 0x00000008;       // PRINTER_ACCESS_USE
      if (!OpenPrinter(printer, out h, ref pd))
        return "OpenPrinter loi " + Marshal.GetLastWin32Error();
    }
    try {
      DeleteForm(h, name);
      FORM_INFO_1 f = new FORM_INFO_1();
      f.Flags = 0;
      f.pName = name;
      f.Size.cx = (int)Math.Round(wmm * 1000.0);
      f.Size.cy = (int)Math.Round(hmm * 1000.0);
      f.ImageableArea.left = 0; f.ImageableArea.top = 0;
      f.ImageableArea.right = f.Size.cx; f.ImageableArea.bottom = f.Size.cy;
      if (!AddForm(h, 1, ref f))
        return "AddForm loi " + Marshal.GetLastWin32Error();
      return null;
    } finally { ClosePrinter(h); }
  }
}
'@
$names = @()
if ($target) { $names += $target.Name }
$names += @($printers | Where-Object { -not $target -or $_.Name -ne $target.Name } | Select-Object -ExpandProperty Name)
$created = $false
foreach ($pn in $names) {
  $e = [HskForm]::AddLabelForm($pn, 'Hasaki 88x10', 88, 10)
  if ($e) { continue }
  $e = [HskForm]::AddLabelForm($pn, 'Hasaki 105x22', 105, 22)
  if ($e) { continue }
  Write-Host '  [OK] Form he thong Hasaki 88x10 + Hasaki 105x22 (dung chung toan may)'
  $created = $true; break
}
if (-not $created) { Write-Host '  [CHU Y] Khong tao duoc form he thong (khong anh huong may in tem).' }

Write-Host '--- Buoc 3/3: tat Dau trang va chan trang (Chrome + Edge) ---'
foreach ($root in 'HKLM:\SOFTWARE\Policies\Google\Chrome', 'HKLM:\SOFTWARE\Policies\Microsoft\Edge') {
  New-Item -Path $root -Force | Out-Null
  New-ItemProperty -Path $root -Name 'PrintHeaderFooter' -PropertyType DWord -Value 0 -Force | Out-Null
}
Write-Host '  [OK] Da tat qua chinh sach may'

Write-Host ''
Write-Host '=== XONG! Cach in: mo Chrome vao web in tem, go ma -> Enter ==='
Write-Host '  (dung barcode.hasaki.vn; neu khong vao duoc thi barcode1.hasaki.vn)'
Write-Host 'Lan dau tren may nay, trong hop thoai in chon 1 lan (Chrome se tu nho):'
Write-Host '  - May in dich  : may in tem (TSC PE200 / Honeywell PC42t plus)'
Write-Host '  - Kho giay     : Hasaki 88x10 (cuon tem 21x10)  hoac  Hasaki 105x22 (cuon 35x22)'
Write-Host '  - Le           : Khong co (None)'
Write-Host '  - Ty le        : Tuy chinh -> 100'
Write-Host 'Xem truoc phai THAY ma vach roi moi bam In.'
try { Stop-Transcript | Out-Null } catch {}
