# 設置編碼為 UTF-8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

# 檢查是否具有管理員權限
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)

if (-not $isAdmin) {
    Write-Host "需要管理員權限來操作服務，正在請求提升權限..."
    Start-Process powershell -ArgumentList "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs
    exit
}

# # 設定工作目錄為腳本所在位置
$scriptPath = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location -Path $scriptPath

# 停止 WM_CMS 服務
Write-Host "正在停止 WM_CMS 服務..."
Stop-Service -Name "WM_CMS" -Force -ErrorAction SilentlyContinue

# 等待服務完全停止
do {
    Start-Sleep -Seconds 1
    $service = Get-Service -Name "WM_CMS" -ErrorAction SilentlyContinue
} while ($service -and $service.Status -ne 'Stopped')

# 備份原本的wmcms資料夾
$today = (Get-Date).ToString("yyyyMMdd_HHmmss")
if (Test-Path "D:\wmcms") {
    # 確保備份目錄存在
    if (-not (Test-Path "D:\bk")) {
        New-Item -ItemType Directory -Path "D:\bk"
    }
    
    # 先將wmcms改名並直接移動到bk目錄
    Rename-Item -Path "D:\wmcms" -NewName "wmcms_bk_$today"
    Move-Item -Path "D:\wmcms_bk_$today" -Destination "D:\bk"
}
# 解壓縮 WMCMS.zip 檔案到wmcms資料夾
Write-Host "解壓縮 WMCMS.zip ..."
Write-Host "`n`n"
Expand-Archive -Path "$scriptPath\WMCMS.zip" -DestinationPath "D:\wmcms" -Force
Write-Host "`n"

# 處理並複製 config.json ...
Write-Host "處理並複製 config.json ..."
try {
    # 使用 UTF8 編碼讀取檔案
    $rawContent = [System.IO.File]::ReadAllText("D:\config.json", [System.Text.Encoding]::UTF8)
    $configContent = $rawContent | ConvertFrom-Json
    $newConfig = @{
        ENV = $configContent.ENV
        SITE_URL = $configContent.SITE_URL
        API_URL = $configContent.API_URL
        Encrypted = $configContent.Encrypted
    }
    # 確保輸出的 JSON 格式正確
    $newJsonContent = $newConfig | ConvertTo-Json -Depth 10
    [System.IO.File]::WriteAllText("D:\wmcms\dist\config.json", $newJsonContent, [System.Text.Encoding]::UTF8)
} catch {
    Write-Host "處理 config.json 時發生錯誤：" -ForegroundColor Red
    Write-Host $_.Exception.Message
    exit 1
}

# 啟動 WM_CMS 服務
Write-Host "正在啟動 WM_CMS 服務..."
Start-Service -Name "WM_CMS" -ErrorAction SilentlyContinue

# 等待服務啟動完成
do {
    Start-Sleep -Seconds 1
    $service = Get-Service -Name "WM_CMS" -ErrorAction SilentlyContinue
} while ($service -and $service.Status -ne 'Running')

Write-Host "服務已啟動完成！"
pause