const fs = require('fs');
const { Client } = require('ssh2');

const scriptContent = fs.readFileSync('/home/node/.openclaw/workspace/tasks/enduro-trails/prototype/scripts/download_srtm_all7.sh', 'utf8');
const conn = new Client();

conn.on('ready', () => {
  console.log('SSH connected. Uploading script...');
  conn.sftp((err, sftp) => {
    if (err) { console.error('SFTP error:', err); conn.end(); return; }
    const stream = sftp.createWriteStream('/home/slin/enduro-trails/data/download_srtm7.sh');
    stream.end(scriptContent);
    stream.on('close', () => {
      console.log('Script uploaded. Starting background download...');
      conn.exec('chmod +x /home/slin/enduro-trails/data/download_srtm7.sh && nohup bash /home/slin/enduro-trails/data/download_srtm7.sh > /home/slin/enduro-trails/data/srtm_download7.log 2>&1 & echo "PID=$!"', (err, stream) => {
        if (err) { console.error('Exec error:', err); conn.end(); return; }
        let out = '';
        stream.on('data', d => out += d);
        stream.on('close', () => {
          console.log('Started:', out.trim());
          conn.end();
        });
      });
    });
  });
});

conn.on('error', (err) => {
  console.error('SSH error:', err.message);
  process.exit(1);
});

conn.connect({
  host: '82.22.50.71',
  username: 'slin',
  password: 'motoZ@yaz2010',
  readyTimeout: 30000
});
