# 3588AdminBackend Windows 构建脚本
# 在 Windows 上交叉编译 Linux 版本并打包

# 配置
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$ProjectDir = Split-Path -Parent (Split-Path -Parent $ScriptDir)
$BuildDir = "$ProjectDir\build"
$PackageName = "3588AdminBackend-离线部署包-$(Get-Date -Format 'yyyyMMdd')"
$PackageDir = "$BuildDir\$PackageName"

Write-Host "========== 3588AdminBackend Windows 构建 ==========" -ForegroundColor Green
Write-Host "项目目录: $ProjectDir"
Write-Host "构建目录: $BuildDir"
Write-Host ""

# 检查 Go
$GoVersion = go version 2>$null
if ($LASTEXITCODE -ne 0) {
    Write-Host "错误: 未找到 Go 命令，请先安装 Go" -ForegroundColor Red
    exit 1
}
Write-Host "Go 版本: $GoVersion"
Write-Host ""

# 清理旧构建
Write-Host "[1/6] 清理旧构建..."
if (Test-Path $BuildDir) {
    Remove-Item -Recurse -Force $BuildDir
}
New-Item -ItemType Directory -Path $PackageDir -Force | Out-Null

# 创建目录结构
Write-Host "[2/6] 创建目录结构..."
New-Item -ItemType Directory -Path "$PackageDir\bin" -Force | Out-Null
New-Item -ItemType Directory -Path "$PackageDir\config" -Force | Out-Null
New-Item -ItemType Directory -Path "$PackageDir\scripts" -Force | Out-Null
New-Item -ItemType Directory -Path "$PackageDir\docs" -Force | Out-Null
New-Item -ItemType Directory -Path "$PackageDir\systemd" -Force | Out-Null

# 编译项目
Write-Host "[3/6] 交叉编译 Linux AMD64 版本..."
cd $ProjectDir

$env:GOOS = "linux"
$env:GOARCH = "amd64"
$env:GOTOOLCHAIN = "local"

go build -ldflags="-s -w" -o "$PackageDir\bin\managerd" ./cmd/managerd

if ($LASTEXITCODE -ne 0 -or -not (Test-Path "$PackageDir\bin\managerd")) {
    Write-Host "错误: 编译失败" -ForegroundColor Red
    exit 1
}

Write-Host "  编译成功" -ForegroundColor Green

# 复制配置文件
Write-Host "[4/6] 复制配置文件..."
if (Test-Path "$ProjectDir\managerd.json") {
    Copy-Item "$ProjectDir\managerd.json" "$PackageDir\config\managerd.json.example"
} else {
    @"
{
  "listen": "0.0.0.0:18080",
  "discovery_port": 35688,
  "discovery_timeout_ms": 1200,
  "offline_after_ms": 10000,
  "agent_token": "CHANGE_ME",
  "concurrency": 5
}
"@ | Out-File -FilePath "$PackageDir\config\managerd.json.example" -Encoding UTF8
}

# 复制模板文件（如果有）
if (Test-Path "$ProjectDir\templates") {
    Write-Host "  复制模板文件..."
    Copy-Item -Recurse "$ProjectDir\templates" "$PackageDir\"
}

# 复制脚本
Write-Host "[5/6] 复制部署脚本..."
Copy-Item "$ScriptDir\3588admin" "$PackageDir\scripts\"
Copy-Item "$ScriptDir\3588admin.service" "$PackageDir\systemd\"

# 修复换行符为 LF（Unix 格式）
$scriptContent = Get-Content "$PackageDir\scripts\3588admin" -Raw
$scriptContent = $scriptContent -replace "`r`n", "`n"
Set-Content -Path "$PackageDir\scripts\3588admin" -Value $scriptContent -NoNewLine

$serviceContent = Get-Content "$PackageDir\systemd\3588admin.service" -Raw
$serviceContent = $serviceContent -replace "`r`n", "`n"
Set-Content -Path "$PackageDir\systemd\3588admin.service" -Value $serviceContent -NoNewLine

# 复制文档
Write-Host "[6/6] 复制文档..."
if (Test-Path "$ProjectDir\docs") {
    Get-ChildItem "$ProjectDir\docs\*.md" -ErrorAction SilentlyContinue | ForEach-Object {
        Copy-Item $_.FullName "$PackageDir\docs\"
    }
}
if (Test-Path "$ProjectDir\Readme.md") {
    Copy-Item "$ProjectDir\Readme.md" "$PackageDir\docs\"
}
if (Test-Path "$ProjectDir\API_Device_RemoteMgmt_InterfaceTable.md") {
    Copy-Item "$ProjectDir\API_Device_RemoteMgmt_InterfaceTable.md" "$PackageDir\docs\"
}

# 创建版本信息
@"
3588AdminBackend 离线部署包
版本: 1.0.0
构建时间: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')
Go版本: $GoVersion
目标系统: Ubuntu 22.04.5 LTS x86_64
构建主机: $env:COMPUTERNAME (Windows)
"@ | Out-File -FilePath "$PackageDir\VERSION" -Encoding UTF8

# 创建快速安装说明
@"
╔══════════════════════════════════════════════════════════════╗
║         3588AdminBackend 离线部署包 - 快速安装指南            ║
╚══════════════════════════════════════════════════════════════╝

【系统要求】
  - Ubuntu 22.04.5 LTS (x86_64)
  - root 权限
  
【重要说明】
  ✓ 本部署包已包含静态编译的二进制文件
  ✓ 目标机器无需安装 Go 运行时
  ✓ 无需互联网连接（纯离线安装）
  ✓ 二进制文件在 Windows 上交叉编译生成

【安装步骤】

1. 上传部署包到 Ubuntu 服务器
   scp -r $PackageName.tar.gz user@ubuntu-server:/tmp/

2. 解压部署包
   tar -xzf $PackageName.tar.gz
   cd $PackageName/

3. 执行安装
   sudo ./scripts/3588admin install

4. 修改配置
   sudo nano /opt/3588admin/config/managerd.json
   
   重点修改:
   - agent_token: 修改为安全的随机字符串
   - listen: 如需外部访问改为 "0.0.0.0:18080"

5. 启动服务
   sudo 3588admin start

6. 验证安装
   sudo 3588admin status

【常用命令】
  3588admin start     - 启动服务
  3588admin stop      - 停止服务  
  3588admin status    - 查看状态
  3588admin restart   - 重启服务
  3588admin upgrade   - 升级服务
  3588admin uninstall - 卸载服务
  3588admin check     - 检查环境

【快捷命令】
  3588admin-start     - 启动服务
  3588admin-stop      - 停止服务
  3588admin-status    - 查看状态

【文件位置】
  安装目录: /opt/3588admin
  配置文件: /opt/3588admin/config/managerd.json
  日志文件: /opt/3588admin/logs/managerd.log

【问题排查】
  1. 查看日志: tail -f /opt/3588admin/logs/managerd.log
  2. 检查配置: python3 -m json.tool /opt/3588admin/config/managerd.json
  3. 检查端口: sudo netstat -tlnp | grep managerd

【防火墙】
  sudo ufw allow 18080/tcp   # HTTP API
  sudo ufw allow 35688/udp   # UDP 发现

"@ | Out-File -FilePath "$PackageDir\README-离线安装.txt" -Encoding UTF8

# 打包（使用 tar，Windows 10/11 内置）
Write-Host ""
Write-Host "打包..."
cd $BuildDir

# 创建 tar.gz 包（使用正斜杠避免 Windows 路径问题）
$PackageNameUnix = $PackageName -replace '\\', '/'
tar -czf "$PackageName.tar.gz" "$PackageNameUnix"

if ($LASTEXITCODE -eq 0 -and (Test-Path "$PackageName.tar.gz")) {
    Write-Host ""
    Write-Host "========== 构建完成 ==========" -ForegroundColor Green
    Write-Host ""
    Write-Host "输出文件:"
    Get-ChildItem "$PackageName.tar.gz" | ForEach-Object {
        $size = [math]::Round($_.Length / 1MB, 2)
        Write-Host "  $($_.Name) ($size MB)"
    }
    Write-Host ""
    Write-Host "部署包位置: $BuildDir\$PackageName.tar.gz" -ForegroundColor Yellow
    Write-Host ""
    Write-Host "使用说明:"
    Write-Host "1. 将 $PackageName.tar.gz 上传到 Ubuntu 服务器"
    Write-Host "2. 解压并运行: sudo ./scripts/3588admin install"
    Write-Host ""
} else {
    Write-Host "错误: 打包失败" -ForegroundColor Red
    exit 1
}
