setup.ps1 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. # docx Environment Setup & Initialization Script (Windows PowerShell)
  2. # Mirror of setup.sh — Windows 10/11 + Windows Server 2019+
  3. # Requires: PowerShell 5.1+ (Windows-shipped) or PowerShell 7+ (pwsh)
  4. # Goals (parity with setup.sh):
  5. # - dotnet >= 9
  6. # - python (3.x), pandoc, LibreOffice (soffice.exe), poppler (pdftoppm.exe), zip/unzip
  7. # - UTF-8 console (CRITICAL: dotnet build of the bundled project will fail on GBK consoles
  8. # because some C# samples carry CJK content)
  9. # - Same [OK] / [WARN] / [FAIL] / [INFO] / === === lines as setup.sh
  10. # - Same exit codes (0 success / 1 fatal / 2 unsupported shell)
  11. #Requires -Version 5.1
  12. [CmdletBinding()]
  13. param(
  14. [ValidateSet('Read', 'Render', 'Full')]
  15. [string]$Level = 'Full',
  16. [switch]$Minimal,
  17. [switch]$SkipVerify,
  18. [switch]$Help
  19. )
  20. $ErrorActionPreference = "Stop"
  21. # Force UTF-8 for THIS session AND its child native processes (dotnet build / pandoc / soffice).
  22. # [Console]::OutputEncoding only affects PowerShell's view of stdout. The active console code page
  23. # (chcp) is what child native processes inherit, and CN/JP/KR Windows ships with chcp 936/932/949.
  24. # Bundled C# Sample files contain CJK string literals WITHOUT a UTF-8 BOM, so `dotnet build` will
  25. # fail on a non-UTF-8 console code page. chcp must come BEFORE the [Console]::OutputEncoding
  26. # assignment so we don't double-flip the encoding.
  27. try { & chcp.com 65001 *> $null } catch { } # chcp.com missing on Nano Server / WSL pwsh — fall through
  28. [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
  29. [Console]::InputEncoding = [System.Text.Encoding]::UTF8
  30. $OutputEncoding = [System.Text.UTF8Encoding]::new()
  31. # PS 5.1 default Invoke-WebRequest only enables Ssl3 + Tls1.0; dotnet-install endpoint requires
  32. # TLS 1.2+ since 2020. Enable Tls12/Tls13 globally for this session before any IWR call.
  33. try {
  34. [Net.ServicePointManager]::SecurityProtocol =
  35. [Net.ServicePointManager]::SecurityProtocol -bor `
  36. [Net.SecurityProtocolType]::Tls12 -bor `
  37. [Net.SecurityProtocolType]::Tls11
  38. if ([enum]::GetNames([Net.SecurityProtocolType]) -contains 'Tls13') {
  39. [Net.ServicePointManager]::SecurityProtocol =
  40. [Net.ServicePointManager]::SecurityProtocol -bor `
  41. [Net.SecurityProtocolType]::Tls13
  42. }
  43. } catch { } # rare environments lack the enum; let IWR fail loudly later
  44. $env:DOTNET_CLI_UI_LANGUAGE = 'en'
  45. $ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
  46. $ProjectDir = Split-Path -Parent $ScriptDir
  47. $DotnetDir = Join-Path $ScriptDir 'dotnet'
  48. $LogFile = Join-Path $ProjectDir '.setup.log'
  49. $DotnetRequiredMajor = 9
  50. # --- Output helpers (parity with setup.sh log/warn/fail/info/step) ---
  51. function Write-Log { param([Parameter(ValueFromRemainingArguments = $true)]$Msg) Write-Host ("[OK] " + ($Msg -join ' ')) -ForegroundColor Green }
  52. function Write-Warn { param([Parameter(ValueFromRemainingArguments = $true)]$Msg) Write-Host ("[WARN] " + ($Msg -join ' ')) -ForegroundColor Yellow }
  53. function Write-Fail { param([Parameter(ValueFromRemainingArguments = $true)]$Msg) Write-Host ("[FAIL] " + ($Msg -join ' ')) -ForegroundColor Red }
  54. function Write-Info { param([Parameter(ValueFromRemainingArguments = $true)]$Msg) Write-Host ("[INFO] " + ($Msg -join ' ')) -ForegroundColor Cyan }
  55. function Write-Step { param([Parameter(ValueFromRemainingArguments = $true)]$Msg) Write-Host ("`n=== " + ($Msg -join ' ') + " ===") -ForegroundColor Blue }
  56. if ($Help) {
  57. @"
  58. Usage: setup.ps1 [-Level Read|Render|Full] [-Minimal] [-SkipVerify] [-Help]
  59. -Level Read Only install/verify the read gate (python, unzip/tar, UTF-8)
  60. -Level Render Above + soffice + pdftoppm
  61. -Level Full Above + dotnet >= $DotnetRequiredMajor + pandoc + zip + project build (default)
  62. -Minimal Skip optional checks (fonts only)
  63. -SkipVerify Skip the final create-document verification
  64. -Help Show this help
  65. "@ | Write-Host
  66. exit 0
  67. }
  68. Write-Host "============================================"
  69. Write-Host " docx Setup & Initialization (Windows)"
  70. Write-Host " $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
  71. Write-Host " Level: $Level"
  72. Write-Host "============================================"
  73. "" | Set-Content -Path $LogFile -Encoding UTF8
  74. # --- Detect package manager ---
  75. function Test-Command($Name) { [bool](Get-Command $Name -ErrorAction SilentlyContinue) }
  76. $HasWinget = Test-Command winget
  77. $HasChoco = Test-Command choco
  78. $HasScoop = Test-Command scoop
  79. if ($HasWinget) { Write-Info "Package manager: winget" }
  80. elseif ($HasChoco) { Write-Info "Package manager: chocolatey" }
  81. elseif ($HasScoop) { Write-Info "Package manager: scoop" }
  82. else { Write-Warn "No package manager found (winget/choco/scoop). Manual install may be needed." }
  83. function Add-PathForSession([string]$Dir) {
  84. if (-not $Dir -or -not (Test-Path $Dir)) { return }
  85. if (-not (($env:Path -split [IO.Path]::PathSeparator) -contains $Dir)) {
  86. $env:Path = $Dir + [IO.Path]::PathSeparator + $env:Path
  87. }
  88. }
  89. # Pull whatever Machine/User PATH the registry currently holds, MERGE it with the existing
  90. # session PATH (so any session-only Add-PathForSession entries from earlier in this script are
  91. # preserved), and dedup. Naively re-assigning $env:Path = "$machine;$user" wipes session-only
  92. # entries that have not been written to the registry yet — that was the original bug.
  93. function Sync-PathFromMachineUser {
  94. $machine = [Environment]::GetEnvironmentVariable('Path', 'Machine')
  95. $user = [Environment]::GetEnvironmentVariable('Path', 'User')
  96. $sep = [IO.Path]::PathSeparator
  97. $sessionExtras = @()
  98. foreach ($entry in ($env:Path -split $sep)) {
  99. if (-not $entry) { continue }
  100. $inMachine = ($machine -and ($machine -split $sep) -contains $entry)
  101. $inUser = ($user -and ($user -split $sep) -contains $entry)
  102. if (-not ($inMachine -or $inUser)) { $sessionExtras += $entry }
  103. }
  104. $merged = @()
  105. foreach ($entry in @($sessionExtras + ($machine -split $sep) + ($user -split $sep))) {
  106. if (-not $entry) { continue }
  107. if ($merged -notcontains $entry) { $merged += $entry }
  108. }
  109. $env:Path = ($merged -join $sep)
  110. }
  111. # Back-compat alias for any external doc that still mentions the old name; new code MUST use
  112. # Sync-PathFromMachineUser. The ordering bug was: callers did Add-PathForSession then Refresh,
  113. # and Refresh wiped the just-added entry. Sync-* preserves session-only entries.
  114. Set-Alias -Name Refresh-PathFromMachineUser -Value Sync-PathFromMachineUser
  115. # Replacement for `Tee-Object -FilePath $LogFile -Append` whose default encoding in PS 5.1 is
  116. # ANSI/Default (mojibakes CJK in the install log). Add-Content -Encoding UTF8 is the only
  117. # reliable way on 5.1 to append UTF-8 without reopening/rewriting the file.
  118. function Append-LogUtf8 {
  119. [CmdletBinding()]
  120. param([Parameter(ValueFromPipeline = $true)] $InputObject)
  121. process {
  122. $line = if ($null -eq $InputObject) { '' } else { "$InputObject" }
  123. Add-Content -LiteralPath $script:LogFile -Value $line -Encoding UTF8
  124. # Re-emit so the original Tee-Object behavior (also write to console / downstream) holds.
  125. $InputObject
  126. }
  127. }
  128. function Install-WithPkgMgr {
  129. param(
  130. [Parameter(Mandatory)] [string]$Tool,
  131. [string]$WingetId,
  132. [string]$ChocoId,
  133. [string]$ScoopId,
  134. [string]$ManualUrl
  135. )
  136. Write-Info "Installing $Tool ..."
  137. if ($HasWinget -and $WingetId) {
  138. & winget install --id $WingetId --silent --accept-source-agreements --accept-package-agreements 2>&1 | Append-LogUtf8
  139. }
  140. elseif ($HasChoco -and $ChocoId) {
  141. & choco install $ChocoId -y --no-progress 2>&1 | Append-LogUtf8
  142. }
  143. elseif ($HasScoop -and $ScoopId) {
  144. & scoop install $ScoopId 2>&1 | Append-LogUtf8
  145. }
  146. else {
  147. Write-Fail "Cannot auto-install $Tool. Install it manually: $ManualUrl"
  148. return $false
  149. }
  150. Refresh-PathFromMachineUser
  151. return $true
  152. }
  153. # --- Resolve soffice.exe across the usual install layouts ---
  154. function Resolve-SofficePath {
  155. $cmd = Get-Command soffice.exe -ErrorAction SilentlyContinue
  156. if ($cmd) { return $cmd.Source }
  157. $cmd = Get-Command soffice -ErrorAction SilentlyContinue
  158. if ($cmd) { return $cmd.Source }
  159. $candidates = @(
  160. (Join-Path $env:ProgramFiles 'LibreOffice\program\soffice.exe'),
  161. (Join-Path ${env:ProgramFiles(x86)} 'LibreOffice\program\soffice.exe'),
  162. (Join-Path $env:LOCALAPPDATA 'Programs\LibreOffice\program\soffice.exe'),
  163. (Join-Path $env:LOCALAPPDATA 'Microsoft\WinGet\Links\soffice.exe'),
  164. (Join-Path $env:USERPROFILE 'scoop\apps\libreoffice\current\program\soffice.exe')
  165. ) | Where-Object { $_ }
  166. foreach ($p in $candidates) {
  167. if (Test-Path $p) { return (Resolve-Path $p).Path }
  168. }
  169. return $null
  170. }
  171. # --- Resolve pdftoppm.exe (poppler) ---
  172. function Resolve-PdftoppmPath {
  173. $cmd = Get-Command pdftoppm.exe -ErrorAction SilentlyContinue
  174. if ($cmd) { return $cmd.Source }
  175. $cmd = Get-Command pdftoppm -ErrorAction SilentlyContinue
  176. if ($cmd) { return $cmd.Source }
  177. $candidates = @(
  178. (Join-Path $env:USERPROFILE 'scoop\apps\poppler\current\bin\pdftoppm.exe'),
  179. (Join-Path $env:ProgramData 'chocolatey\bin\pdftoppm.exe')
  180. ) | Where-Object { $_ }
  181. foreach ($p in $candidates) { if (Test-Path $p) { return (Resolve-Path $p).Path } }
  182. return $null
  183. }
  184. # --- Resolve python (Windows ships `py` launcher; we want `python` callable) ---
  185. function Resolve-PythonCommand {
  186. foreach ($name in @('python', 'python3', 'py')) {
  187. $cmd = Get-Command $name -ErrorAction SilentlyContinue
  188. if (-not $cmd) { continue }
  189. if ($name -eq 'py') {
  190. try {
  191. & $cmd.Source -3 --version *> $null
  192. if ($LASTEXITCODE -eq 0) { return @{ Cmd = $cmd.Source; Args = @('-3') } }
  193. } catch { continue }
  194. } else {
  195. return @{ Cmd = $cmd.Source; Args = @() }
  196. }
  197. }
  198. return $null
  199. }
  200. # ============ READ-LEVEL DEPS ============
  201. function Install-Python {
  202. Write-Step "Checking python (>= 3.9)"
  203. $py = Resolve-PythonCommand
  204. if ($py) {
  205. $verLine = (& $py.Cmd @($py.Args + '--version') 2>&1) -join ' '
  206. Write-Log "python available: $($py.Cmd) ($verLine)"
  207. return $true
  208. }
  209. if (-not (Install-WithPkgMgr -Tool 'python' `
  210. -WingetId 'Python.Python.3.12' `
  211. -ChocoId 'python' `
  212. -ScoopId 'python' `
  213. -ManualUrl 'https://www.python.org/downloads/windows/')) { return $false }
  214. $py = Resolve-PythonCommand
  215. if (-not $py) { Write-Fail 'python installation finished but the command is still not on PATH'; return $false }
  216. Write-Log "python installed: $($py.Cmd)"
  217. return $true
  218. }
  219. function Install-UnzipFallback {
  220. Write-Step "Checking unzip / tar.exe"
  221. if (Test-Command tar) {
  222. # tar.exe ships with Windows 10 1803+ and handles .zip natively.
  223. Write-Log "tar.exe available (handles .zip on Windows 10+)"
  224. return $true
  225. }
  226. if (Test-Command unzip) {
  227. Write-Log "unzip available"
  228. return $true
  229. }
  230. Write-Warn "Neither tar.exe nor unzip found. Falling back to PowerShell Expand-Archive at runtime."
  231. Write-Info "(Expand-Archive ships with PowerShell 5+ so this is a soft warning, not a fatal.)"
  232. return $true
  233. }
  234. function Test-Utf8Console {
  235. Write-Step "Checking console encoding"
  236. $enc = [Console]::OutputEncoding.WebName
  237. $cp = (chcp.com 2>$null | Out-String).Trim()
  238. if ($enc -match '^utf-?8$') {
  239. Write-Log "Console encoding: $enc / $cp"
  240. return $true
  241. }
  242. Write-Warn "Console encoding is $enc / $cp. Forcing UTF-8 for this session."
  243. [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
  244. Write-Info "To make this permanent: 'Settings -> Time & Language -> Language & region -> Administrative -> Change system locale -> Beta: UTF-8'"
  245. return $true
  246. }
  247. function Set-ScriptUnblock {
  248. Write-Step "Unblocking skill scripts (NTFS Mark-of-the-Web)"
  249. Get-ChildItem -Path $ScriptDir -File -Include *.ps1, *.sh -Recurse -ErrorAction SilentlyContinue |
  250. ForEach-Object {
  251. try { Unblock-File -Path $_.FullName -ErrorAction Stop } catch { }
  252. }
  253. Write-Log "scripts unblocked (where applicable)"
  254. }
  255. # ============ RENDER-LEVEL DEPS ============
  256. function Install-Soffice {
  257. Write-Step "Checking LibreOffice/soffice.exe"
  258. $sof = Resolve-SofficePath
  259. if ($sof) {
  260. Write-Log "soffice available: $sof"
  261. Add-PathForSession (Split-Path -Parent $sof)
  262. return $true
  263. }
  264. Write-Info "Installing LibreOffice (this may take a few minutes)..."
  265. if (-not (Install-WithPkgMgr -Tool 'LibreOffice' `
  266. -WingetId 'TheDocumentFoundation.LibreOffice' `
  267. -ChocoId 'libreoffice-fresh' `
  268. -ScoopId 'libreoffice' `
  269. -ManualUrl 'https://www.libreoffice.org/download/')) { return $false }
  270. $sof = Resolve-SofficePath
  271. if (-not $sof) {
  272. Write-Fail "LibreOffice install reported success but soffice.exe is still not discoverable. Add its 'program' directory to PATH and re-run."
  273. return $false
  274. }
  275. Add-PathForSession (Split-Path -Parent $sof)
  276. Write-Log "soffice installed: $sof"
  277. return $true
  278. }
  279. function Install-Poppler {
  280. Write-Step "Checking pdftoppm (poppler)"
  281. $pp = Resolve-PdftoppmPath
  282. if ($pp) { Write-Log "pdftoppm available: $pp"; return $true }
  283. if (-not (Install-WithPkgMgr -Tool 'poppler' `
  284. -WingetId 'oschwartz10612.Poppler' `
  285. -ChocoId 'poppler' `
  286. -ScoopId 'poppler' `
  287. -ManualUrl 'https://github.com/oschwartz10612/poppler-windows/releases')) { return $false }
  288. $pp = Resolve-PdftoppmPath
  289. if (-not $pp) { Write-Fail "poppler install reported success but pdftoppm.exe is still not discoverable"; return $false }
  290. Add-PathForSession (Split-Path -Parent $pp)
  291. Write-Log "pdftoppm installed: $pp"
  292. return $true
  293. }
  294. # ============ FULL-LEVEL DEPS ============
  295. function Install-DotnetSdk {
  296. Write-Step "Checking .NET SDK (>= $DotnetRequiredMajor.0)"
  297. if (Test-Command dotnet) {
  298. $verRaw = (& dotnet --version) 2>$null
  299. if ($verRaw) {
  300. try {
  301. $major = [int](($verRaw -split '\.')[0])
  302. if ($major -ge $DotnetRequiredMajor) {
  303. Write-Log "dotnet $verRaw already installed (>= $DotnetRequiredMajor.0 OK)"
  304. return $true
  305. }
  306. Write-Warn "dotnet $verRaw found but < $DotnetRequiredMajor.0, upgrading..."
  307. } catch { Write-Warn "Could not parse dotnet --version output ('$verRaw'), reinstalling" }
  308. }
  309. }
  310. # Prefer the official Channel install via dotnet-install.ps1 (no admin, lands in $env:USERPROFILE\.dotnet)
  311. Write-Info "Installing .NET SDK $DotnetRequiredMajor via dotnet-install.ps1 (user-scope, no sudo)..."
  312. $installerPath = Join-Path $env:TEMP "dotnet-install.ps1"
  313. try {
  314. Invoke-WebRequest -Uri 'https://dot.net/v1/dotnet-install.ps1' -OutFile $installerPath -UseBasicParsing
  315. } catch {
  316. Write-Warn "Could not download dotnet-install.ps1: $_"
  317. if (-not (Install-WithPkgMgr -Tool '.NET SDK' `
  318. -WingetId "Microsoft.DotNet.SDK.$DotnetRequiredMajor" `
  319. -ChocoId 'dotnet-sdk' `
  320. -ScoopId 'dotnet-sdk' `
  321. -ManualUrl "https://dotnet.microsoft.com/download/dotnet/$DotnetRequiredMajor.0")) { return $false }
  322. }
  323. if (Test-Path $installerPath) {
  324. $dotnetRoot = Join-Path $env:USERPROFILE '.dotnet'
  325. & powershell -ExecutionPolicy Bypass -File $installerPath -Channel "$DotnetRequiredMajor.0" -InstallDir $dotnetRoot 2>&1 |
  326. Append-LogUtf8 | Out-Null
  327. # NOTE: do NOT Sync-PathFromMachineUser here. dotnet-install.ps1 (user-scope) installs to
  328. # $USERPROFILE\.dotnet but does NOT modify the registry PATH; syncing would still preserve
  329. # the session-only Add we're about to do, but no useful work would happen. Just Add and
  330. # move on.
  331. Add-PathForSession $dotnetRoot
  332. }
  333. if (-not (Test-Command dotnet)) {
  334. Write-Fail "dotnet installation failed"
  335. return $false
  336. }
  337. Write-Log "dotnet $(& dotnet --version) installed"
  338. return $true
  339. }
  340. function Install-Pandoc {
  341. Write-Step "Checking pandoc"
  342. if (Test-Command pandoc) {
  343. $pv = (& pandoc --version | Select-Object -First 1)
  344. Write-Log "pandoc already installed ($pv)"
  345. return $true
  346. }
  347. if (-not (Install-WithPkgMgr -Tool 'pandoc' `
  348. -WingetId 'JohnMacFarlane.Pandoc' `
  349. -ChocoId 'pandoc' `
  350. -ScoopId 'pandoc' `
  351. -ManualUrl 'https://pandoc.org/installing.html')) { return $false }
  352. if (-not (Test-Command pandoc)) { Write-Fail 'pandoc installation failed'; return $false }
  353. Write-Log "pandoc installed"
  354. return $true
  355. }
  356. function Install-ZipTools {
  357. Write-Step "Checking zip / Compress-Archive"
  358. if (Test-Command zip) { Write-Log "zip available"; return $true }
  359. # Compress-Archive is built into PowerShell 5+; treat as zip equivalent for skill needs.
  360. if (Get-Command Compress-Archive -ErrorAction SilentlyContinue) {
  361. Write-Log "Compress-Archive cmdlet available (zip equivalent)"
  362. return $true
  363. }
  364. Write-Warn "Neither zip nor Compress-Archive available. DOCX repacking may fail."
  365. return $true
  366. }
  367. function Test-NugetConfig {
  368. Write-Step "Checking NuGet configuration"
  369. try {
  370. $sources = & dotnet nuget list source 2>$null
  371. if ($sources -and ($sources -match 'nuget.org')) {
  372. Write-Log 'nuget.org source is configured'
  373. return
  374. }
  375. Write-Warn 'nuget.org not in sources. Adding...'
  376. & dotnet nuget add source 'https://api.nuget.org/v3/index.json' --name 'nuget.org' 2>&1 |
  377. Append-LogUtf8 | Out-Null
  378. } catch {
  379. Write-Warn "Could not validate NuGet sources: $_"
  380. }
  381. }
  382. function Build-DotnetProject {
  383. Write-Step "Building docx .NET project"
  384. if (-not (Test-Path $DotnetDir)) {
  385. Write-Fail "Dotnet project directory not found: $DotnetDir"
  386. return $false
  387. }
  388. Push-Location $DotnetDir
  389. try {
  390. Write-Info "Restoring NuGet packages..."
  391. & dotnet restore --verbosity quiet 2>&1 | Append-LogUtf8 | Out-Null
  392. if ($LASTEXITCODE -ne 0) {
  393. Write-Fail "NuGet restore failed. Common causes: no internet / corporate proxy blocking nuget.org / disk full."
  394. Write-Info "Diagnose with: dotnet restore --verbosity detailed"
  395. return $false
  396. }
  397. Write-Log "NuGet packages restored"
  398. Write-Info "Building project..."
  399. & dotnet build --verbosity quiet --no-restore 2>&1 | Append-LogUtf8 | Out-Null
  400. if ($LASTEXITCODE -ne 0) {
  401. Write-Fail "Build failed. Check $LogFile for details."
  402. return $false
  403. }
  404. Write-Log "Project built successfully"
  405. return $true
  406. } finally {
  407. Pop-Location
  408. }
  409. }
  410. function Test-Verification {
  411. Write-Step "Verification Test"
  412. $testOutput = Join-Path $env:TEMP "docx-setup-test-$PID.docx"
  413. Push-Location $DotnetDir
  414. try {
  415. Write-Info "Creating a test document..."
  416. & dotnet run --project MiniMaxAIDocx.Cli -- create --type report --output $testOutput --title 'Setup Test' 2>&1 |
  417. Append-LogUtf8 | Out-Null
  418. if ($LASTEXITCODE -ne 0 -or -not (Test-Path $testOutput)) {
  419. Write-Fail "Test document creation failed. Check $LogFile for details."
  420. return $false
  421. }
  422. Write-Log "Test document created: $testOutput"
  423. Remove-Item $testOutput -Force -ErrorAction SilentlyContinue
  424. Write-Log "Test passed - docx is ready to use"
  425. return $true
  426. } finally {
  427. Pop-Location
  428. }
  429. }
  430. function Test-Fonts {
  431. Write-Step "Checking fonts"
  432. try {
  433. Add-Type -AssemblyName System.Drawing -ErrorAction Stop
  434. $names = [System.Drawing.FontFamily]::Families | ForEach-Object { $_.Name }
  435. } catch {
  436. Write-Info "Cannot enumerate fonts (System.Drawing unavailable). Skipping."
  437. return
  438. }
  439. if ($names -contains 'Calibri') { Write-Log 'Western fonts: Calibri' } else { Write-Warn 'Calibri missing — install Microsoft Office or fonts pack' }
  440. if ($names -contains 'Times New Roman') { Write-Log 'Western fonts: Times New Roman' } else { Write-Warn 'Times New Roman missing' }
  441. if ($names | Where-Object { $_ -match 'SimSun|Microsoft YaHei|MS Mincho|Malgun Gothic|Noto Sans CJK' }) {
  442. Write-Log 'CJK fonts: available'
  443. } else {
  444. Write-Warn 'CJK fonts not found — install Chinese/Japanese/Korean language packs'
  445. }
  446. }
  447. function Show-Summary {
  448. Write-Step "Setup Complete"
  449. $sof = Resolve-SofficePath; if (-not $sof) { $sof = 'NOT FOUND' }
  450. $pp = Resolve-PdftoppmPath; if (-not $pp) { $pp = 'NOT FOUND' }
  451. $py = Resolve-PythonCommand
  452. $pyDisp = if ($py) { "$($py.Cmd) $($py.Args -join ' ')" } else { 'NOT FOUND' }
  453. $dotnetVer = try { (& dotnet --version 2>$null) } catch { $null }
  454. if (-not $dotnetVer) { $dotnetVer = 'NOT FOUND' }
  455. $pandocVer = try { (& pandoc --version 2>$null | Select-Object -First 1) } catch { $null }
  456. if (-not $pandocVer) { $pandocVer = 'NOT FOUND' }
  457. Write-Host ""
  458. Write-Host (" Environment: Windows {0}" -f [Environment]::OSVersion.Version)
  459. Write-Host (" Level: {0}" -f $Level)
  460. Write-Host (" dotnet: {0}" -f $dotnetVer)
  461. Write-Host (" python: {0}" -f $pyDisp)
  462. Write-Host (" pandoc: {0}" -f $pandocVer)
  463. Write-Host (" pdftoppm: {0}" -f $pp)
  464. Write-Host (" soffice: {0}" -f $sof)
  465. Write-Host (" Project: {0}" -f $DotnetDir)
  466. Write-Host ""
  467. Write-Host (" Mandatory preflight: powershell -ExecutionPolicy Bypass -File {0}\env_check.ps1 -Level Read" -f $ScriptDir)
  468. Write-Host (" Log file: {0}" -f $LogFile)
  469. }
  470. # ============ MAIN ============
  471. $fatal = $false
  472. # Read level (always)
  473. if (-not (Install-Python)) { $fatal = $true }
  474. Install-UnzipFallback | Out-Null
  475. Test-Utf8Console | Out-Null
  476. Set-ScriptUnblock | Out-Null
  477. # Render level
  478. if ($Level -in @('Render', 'Full')) {
  479. if (-not (Install-Soffice)) { $fatal = $true }
  480. if (-not (Install-Poppler)) { $fatal = $true }
  481. }
  482. # Full level
  483. if ($Level -eq 'Full') {
  484. if (-not (Install-DotnetSdk)) { $fatal = $true }
  485. if (-not (Install-Pandoc)) { $fatal = $true }
  486. Install-ZipTools | Out-Null
  487. Test-NugetConfig
  488. if (-not $fatal) {
  489. if (-not (Build-DotnetProject)) { $fatal = $true }
  490. }
  491. }
  492. if (-not $Minimal -and $Level -eq 'Full') { Test-Fonts }
  493. if (-not $fatal -and -not $SkipVerify -and $Level -eq 'Full') {
  494. if (-not (Test-Verification)) { $fatal = $true }
  495. }
  496. Show-Summary
  497. if ($fatal) { exit 1 } else { exit 0 }