# installer/lib.ps1
$ErrorActionPreference = "Stop"

function Ensure-Dirs {
  param([string]$Base = "$env:ProgramData\RicohInstaller")
  $script:BaseDir = $Base
  $script:LogDir  = Join-Path $Base "InstallLogs"
  New-Item -ItemType Directory -Path $script:LogDir -Force | Out-Null
  $script:LogFile = Join-Path $script:LogDir ("install_{0}.log" -f (Get-Date -Format "yyyyMMdd_HHmmss"))
}

function Write-Log([string]$m){
  Add-Content -Path $script:LogFile -Encoding UTF8 -Value ("[{0}] {1}" -f (Get-Date -Format "yyyy-MM-dd HH:mm:ss"), $m)
}

function Assert-Admin {
  $isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()
  ).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)

  if(-not $isAdmin){
    throw "관리자 권한이 필요합니다. 우클릭 → 관리자 권한으로 실행"
  }
}

function RunProc {
  param(
    [Parameter(Mandatory=$true)][string]$File,
    [Parameter(Mandatory=$false)][string[]]$Args = @(),
    [switch]$NoThrow
  )

  Write-Log ("RUN: " + $File + " " + ($Args -join ' '))

  $p = Start-Process -FilePath $File -ArgumentList $Args -Wait -PassThru -NoNewWindow

  Write-Log ("EXIT: " + $p.ExitCode)

  if ($p.ExitCode -ne 0) {
    $msg = "WARN: process nonzero exit: $File (ExitCode=$($p.ExitCode))"
    Write-Log $msg
    if (-not $NoThrow) { throw $msg }
  }
}

