/**
 * 读取Nginx当前活跃配置
 */
const SERVERS = {
  gz: { name: '广州', ip: '43.139.217.141', port: 3910, key: 'zy_gtw_4a155446b7acc09fe46a2a29972c0ca5d9954da19c35dc23' },
}

async function callGatekeeper(server, method, path, body = null) {
  const url = `http://${server.ip}:${server.port}${path}`
  const opts = {
    method,
    headers: { 'Authorization': `Bearer ${server.key}`, 'Content-Type': 'application/json' },
  }
  if (body) opts.body = JSON.stringify(body)
  const res = await fetch(url, opts)
  const text = await res.text()
  let data
  try { data = JSON.parse(text) } catch { data = { raw: text } }
  return { status: res.status, data }
}

async function readFile(server, path) {
  const result = await callGatekeeper(server, 'POST', '/file/read', { path })
  if (result.status === 200) return result.data.content
  return null
}

async function main() {
  const gz = SERVERS.gz
  
  // 读当前活跃配置
  const active = await readFile(gz, '/etc/nginx/sites-enabled/guanghulab')
  console.log('=== 当前活跃配置 (sites-enabled/guanghulab) ===')
  console.log(active)

  // 读模板
  const tpl = await readFile(gz, '/etc/nginx/sites-available/guanghulab.conf')
  if (tpl) {
    console.log('\n=== 模板 (sites-available/guanghulab.conf) ===')
    console.log(tpl.slice(0, 500))
    console.log('...(截断)')
  }
  
  // 测试广州服务器是否能访问新加坡的3912
  console.log('\n=== 网络连通性测试 ===')
  const sgIp = '43.156.237.110'
  const r = await callGatekeeper(gz, 'POST', '/exec', { cmd: `curl -s --connect-timeout 5 http://${sgIp}:3912/ | head -3` })
  console.log(r.data.stdout || r.data.stderr || JSON.stringify(r.data))
}

main().catch(err => console.error('❌', err))
