/**
 * 修复新加坡Nginx：恢复默认配置 + 正确注入/images/
 */

const SG = { ip: '43.156.237.110', port: 3911, key: 'zy_gtw_74d30f54fa8b5581514569ee7874def57861a31ccb2be8c9' }

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

async function exec(srv, cmd) {
  const r = await callGK(srv, 'POST', '/exec', { cmd })
  return r.data
}

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

async function main() {
  // 1. 查看当前损坏的配置
  console.log('📄 当前默认配置:')
  const current = await readFile(SG, '/etc/nginx/sites-enabled/default')
  console.log(current.slice(-500))
  
  // 2. 用sed修复：恢复默认+注入/images/
  // 策略: 找到 "server {" 和第一个 "}" 之间的内容
  // 在第一个server块的末尾（}之前）插入/images/ location
  console.log('\n🔧 用sed修复...')
  
  const result = await exec(SG, `
# 先恢复原始默认配置
cp /etc/nginx/sites-available/default /etc/nginx/sites-enabled/default 2>/dev/null

# 然后在第一个server块最后（}之前）插入/images/ location
sed -i '0,/^server {/{:a;N;\\|^}|!ba|s|\\n}\\n|\\n    # 铸渊图片工作室\n    location /images/ {\n        proxy_pass http://127.0.0.1:3912/;\n        proxy_http_version 1.1;\n        proxy_set_header Host \\$host;\n        proxy_set_header X-Real-IP \\$remote_addr;\n        proxy_set_header X-Forwarded-For \\$proxy_add_x_forwarded_for;\n        proxy_set_header X-Forwarded-Proto \\$scheme;\n        proxy_buffering off;\n        proxy_read_timeout 60s;\n    }\n}\\n|}' /etc/nginx/sites-enabled/default
`)
  console.log('sed结果:', (result.stdout || result.stderr || 'ok').slice(0, 200))

  // 3. 验证
  const fixed = await readFile(SG, '/etc/nginx/sites-enabled/default')
  console.log('\n📄 修复后配置(最后30行):')
  const lines = fixed.split('\n')
  console.log(lines.slice(-30).join('\n'))

  // 4. 测试
  const r1 = await exec(SG, 'nginx -t 2>&1')
  console.log('\nNginx测试:', r1.stdout || r1.stderr)
  
  if (r1.stdout && r1.stdout.includes('test failed')) {
    // sed可能没处理好，用更简单的方法
    console.log('\n⚠️ sed方案失败，用纯Node方案...')
    
    // 重新恢复
    await exec(SG, 'cp /etc/nginx/sites-available/default /etc/nginx/sites-enabled/default 2>/dev/null')
    
    // 用Python来精确插入
    const pyResult = await exec(SG, `
python3 << 'PYEOF'
content = open('/etc/nginx/sites-enabled/default', 'r').read()

# 找到第一个server块的结束位置
# server块以"server {"开始，以"}"结束（不在http块内）
idx = content.find('server {')
if idx >= 0:
    # 找到这个server块的匹配}
    depth = 0
    pos = idx
    while pos < len(content):
        if content[pos] == '{':
            depth += 1
        elif content[pos] == '}':
            depth -= 1
            if depth == 0:
                # 在}之前插入
                insert = '''
    # 铸渊图片工作室 · 代理到本地3912
    location /images/ {
        proxy_pass http://127.0.0.1:3912/;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_buffering off;
        proxy_read_timeout 60s;
    }
'''
                new_content = content[:pos] + insert + content[pos:]
                open('/etc/nginx/sites-enabled/default', 'w').write(new_content)
                print('OK: inserted at position', pos)
                break
        pos += 1
    else:
        print('ERROR: server block not closed')
else:
    print('ERROR: no server block found')
PYEOF
`)
    console.log('Python结果:', pyResult.stdout || pyResult.stderr)
    
    const r2 = await exec(SG, 'nginx -t 2>&1')
    console.log('Nginx测试(重试):', r2.stdout || r2.stderr)
  }

  const r3 = await exec(SG, 'nginx -s reload 2>&1 || systemctl reload nginx 2>&1')
  console.log('Nginx重载:', r3.stdout || r3.stderr || 'ok')
  
  // 最终验证
  const r4 = await exec(SG, 'curl -s http://localhost/images/ | head -3')
  console.log('\n✅ 最终验证 /images/:', r4.stdout || r4.stderr)
}

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