/**
 * 读取站点配置文件
 */
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 exec(server, cmd) {
  const url = `http://${server.ip}:${server.port}/exec`
  const opts = {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${server.key}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ cmd }),
  }
  const res = await fetch(url, opts)
  const data = await res.json()
  return data
}

async function main() {
  const gz = SERVERS.gz

  // 读取关键配置文件
  for (const p of [
    '/etc/nginx/sites-available/forgejo.conf',
    '/etc/nginx/sites-available/guanghulab.conf',
  ]) {
    console.log(`\n📄 ${p}:`)
    const content = await readFile(gz, p)
    if (content) {
      console.log(content)
    } else {
      console.log('  (读取失败或文件不存在)')
    }
  }

  // 看sites-enabled里有什么
  console.log('\n📂 sites-enabled:')
  const r = await exec(gz, 'ls -la /etc/nginx/sites-enabled/ 2>&1')
  console.log(r.stdout || r.stderr)
  
  // 看conf.d
  console.log('\n📂 conf.d:')
  const r2 = await exec(gz, 'ls -la /etc/nginx/conf.d/ 2>&1')
  console.log(r2.stdout || r2.stderr)

  // 查看Forgejo进程
  console.log('\n🔍 Forgejo运行情况:')
  const r3 = await exec(gz, 'ss -tlnp 2>/dev/null | head -20')
  console.log(r3.stdout || r3.stderr)

  // 看guanghulab.com域名的Nginx路由
  console.log('\n🔍 查找server_name:')
  const r4 = await exec(gz, 'grep -rn "server_name" /etc/nginx/ 2>&1')
  console.log(r4.stdout || r4.stderr)

  // 看现有proxy_pass
  console.log('\n🔍 查找proxy_pass:')
  const r5 = await exec(gz, 'grep -rn "proxy_pass" /etc/nginx/ 2>&1')
  console.log(r5.stdout || r5.stderr)
}

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