const User = require('../models/user').User,
  { decrypt } = require('../config/crypto'),
  { exec } = require('child_process'),
  config = require('../config/config'),
  fs = require('fs'),
  SSH = require('simple-ssh');

exports.emailAdmin = callback => {
  User.find({ state: 1 }, (err, users) => {
    let email = '';
    if (err) {
      console.log(err);
      return callback(err);
    } else {
      for (user in users) {
        if (email !== '') email += ', ';
        email += String(users[user].email);
      }
      return callback(null, email);
    }
  });
};

exports.getLinuxUsers = callback => {
  const path = 'cut -d: -f1 /etc/passwd';

  exec(path, (err, stdout, stderr) => {
    if (err) {
      console.log(err);
      return callback(err);
    } else if (stderr) {
      console.log(stderr);
      return callback(stderr);
    } else {
      return callback(null, stdout.split('\n'));
    }
  });
};

// exports.getLinuxId = (users, callback) => {
exports.getLinuxId = callback => {
  const path = 'cut -d: -f3 /etc/passwd';

  exec(path, (err, stdout, stderr) => {
    if (err) {
      console.log(err);
      return callback(err);
    } else if (stderr) {
      console.log(stderr);
      return callback(stderr);
    } else {
      const uid = stdout.split('\n');
      let start = 1000;
      let flag = true;

      while (flag) {
        for (userId in uid) {
          if (Number(uid[userId]) === start) flag = false;
        }
        if (!flag) {
          start++;
          flag = true;
        } else {
          return callback(null, start);
          flag = false;
        }
      }
    }
  });
};

exports.createUser = (uid, user, callback) => {
  const path = `useradd -u ${uid} -g adm -g cdrom -g dip -g plugdev -g lpadmin -g sambashare -d /homeshare/${user.username} -s /bin/bash -m ${user.username}`;

  exec(path, (err, stdout, stderr) => {
    if (err)
      return callback(err);
    else if (stderr)
      return callback(stderr);
    else {
      const passPath = 'echo ' +
        user.username +
        ':' +
        decrypt(user.linux) +
        ' | sudo chpasswd';

      exec(passPath, (err, stdout, stderr) => {
        if (err) return callback(err);
        else if (stderr) return callback(stderr);
        else return callback(null);
      });
    }
  });
};

exports.createUserCluster = (uid, username, callback) => {
  const { user, password, nodes } = config.cluster;

  for (node in nodes) {
    console.log(nodes[node]);
  }

  return callback(null);
};

exports.sshKey = (user, callback) => {
  const ssh = new SSH({
    host: 'localhost',
    // port: 4000,
    user: user.username,
    pass: decrypt(user.linux)
  });

  const pathKey = `ssh-keygen -b 2048 -t rsa -f /homeshare/${user.username}/.ssh/id_rsa -q -N ""`,
    autKeys = `cat /homeshare/${user.username}/.ssh/id_rsa.pub >> /homeshare/${user.username}/.ssh/authorized_keys`;

  ssh
    .exec(pathKey, {
      err: stderr => {
        console.log(stderr);
        return callback(stderr);
      }
    })
    .start();

  ssh
    .exec(autKeys, {
      err: stderr => {
        console.log(stderr);
        return callback(stderr);
      }
    })
    .start();

  ssh
    .exec(`cat >> /homeshare/${user.username}/.bashrc`, {
      in: fs.readFileSync('./helpers/key')
    })
    .start();

  return callback();
};
