const express = require('express')
const { exec, execSync, spawn } = require("child_process");
const { NodeSSH } = require('node-ssh')
const crypto = require('crypto');

const node_ssh = new NodeSSH()

const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  
  console.log("REMOTE_HOST: ", process.env.REMOTE_HOST);
  console.log("REMOTE_USER: ", process.env.REMOTE_USER);
  console.log("SSH_KEY_FILE_NAME: ", process.env.SSH_KEY_FILE_NAME);
  
  const sync_cmd = `ssh -i /root/.ssh/${process.env.SSH_KEY_FILE_NAME} ${process.env.REMOTE_USER}@${process.env.REMOTE_HOST}`

  // I DONT NEED TO SSH. ONLY RSYNC OVER PROTOCOL
  node_ssh.connect({
    host: `${process.env.REMOTE_HOST}`,
    username: `${process.env.REMOTE_USER}`,
    privateKeyPath: `/root/.ssh/${process.env.SSH_KEY_FILE_NAME}`
  })
  .then((data) => {
    console.log('after ssh connect');  
    console.log('data ', data);
  })
  
  

  // const ls = spawn(sync_cmd, ["ls", "-la"]);

  // ls.stdout.on("data", data => {
  //     console.log(`stdout: ${data}`);
  // });
  
  // ls.stderr.on("data", data => {
  //     console.log(`stderr: ${data}`);
  // });
  
  // ls.on('error', (error) => {
  //     console.log(`error: ${error.message}`);
  // });
  
  // ls.on("close", code => {
  //     console.log(`child process exited with code ${code}`);
  // });

// exec(`ssh-keyscan ${process.env.REMOTE_HOST} >> /root/.ssh/known_hosts`, (error, stdout, stderr) => {
//   if (error) {
//     console.error(`exec error: ${error}`);
//     return;
//   }
//   console.log(`stdout: ${stdout}`);
//   console.error(`stderr: ${stderr}`);
// }); 

// exec(sync_cmd, (error, stdout, stderr) => {
//   if (error) {
//     console.error(`exec error: ${error}`);
//     return;
//   }
//   console.log(`stdout: ${stdout}`);
//   console.error(`stderr: ${stderr}`);
// }); 

  console.log(`sprattle running on port ${port}`)
})