const { Client } = require('ssh2');
const conn = new Client();

const HOST = '171.80.3.149';
const PORT = 631;
const USER = 'root';
const PASS = 'aicyRTPZ3868';

const cmds = [
  'mkdir -p /opt/QZMusic-Web/dist/plugins',
  // download all plugins using curl from Alist server
  'curl -sL -o /opt/QZMusic-Web/dist/plugins/zq_kw_v3-fix1.js "http://171.80.3.149:5244/sd/c6VNt7hG/%E9%9F%B3%E6%BA%90/QZ-Music_v2/%E5%AE%98%E6%96%B9/v3/zq_kw_v3-fix1.js?pwd=music"',
  'curl -sL -o /opt/QZMusic-Web/dist/plugins/zq_wy_v3.js "http://171.80.3.149:5244/sd/c6VNt7hG/%E9%9F%B3%E6%BA%90/QZ-Music_v2/%E5%AE%98%E6%96%B9/v3/zq_wy_v3.js?pwd=music"',
  'curl -sL -o /opt/QZMusic-Web/dist/plugins/zq_tx_v3-fix1.js "http://171.80.3.149:5244/sd/c6VNt7hG/%E9%9F%B3%E6%BA%90/QZ-Music_v2/%E5%AE%98%E6%96%B9/v3/zq_tx_v3-fix1.js?pwd=music"',
  'curl -sL -o /opt/QZMusic-Web/dist/plugins/zq_kg.js "http://171.80.3.149:5244/sd/c6VNt7hG/%E9%9F%B3%E6%BA%90/QZ-Music_v2/%E5%AE%98%E6%96%B9/v3/zq_kg.js?pwd=music"',
  'curl -sL -o /opt/QZMusic-Web/dist/plugins/zq_mg_v3.js "http://171.80.3.149:5244/sd/c6VNt7hG/%E9%9F%B3%E6%BA%90/QZ-Music_v2/%E5%AE%98%E6%96%B9/v3/zq_mg_v3.js?pwd=music"',
  'ls -la /opt/QZMusic-Web/dist/plugins/',
];

conn.on('ready', () => {
  console.log('SSH connected');
  runNext(0);
});

function runNext(idx) {
  if (idx >= cmds.length) {
    console.log('All done');
    conn.end();
    return;
  }
  const cmd = cmds[idx];
  console.log(`[${idx+1}/${cmds.length}] ${cmd}`);
  conn.exec(cmd, (err, stream) => {
    if (err) { console.error('Error:', err.message); conn.end(); return; }
    let out = '', errOut = '';
    stream.on('data', d => { out += d.toString(); });
    stream.stderr.on('data', d => { errOut += d.toString(); });
    stream.on('close', code => {
      if (out.trim()) console.log(out.trim());
      if (errOut.trim()) console.error(errOut.trim());
      if (code !== 0) { console.error('Failed (exit ' + code + '), continuing'); }
      runNext(idx + 1);
    });
  });
}

conn.connect({
  host: HOST, port: PORT, username: USER, password: PASS,
  readyTimeout: 30000, keepaliveInterval: 10000,
});
