const User = require('../models/user').User,
  { decrypt } = require('../config/crypto'),
  { exec } = require('child_process'),
  config = require('../config/config'),
  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,cdrom,dip,plugdev,lpadmin,sambashare -d /homeshare/' +
    user.username +
    ' -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);
};
