#!/usr/bin/env node

// This script creates many users to test the UI for such a case

// WARNING keep those in sync with delUsers.js
const USERNAME_PREFIX = 'manyuser';
const PASSOWRD_PREFIX = 'password';
const DISPLAYNAME_PREFIX = 'User ';
const EMAIL_DOMAIN = 'example.com'; // addresses will be username@EMAIL_DOMAIN
const COUNT = 100;

var async = require('async'),
    readlineSync = require('readline-sync'),
    superagent = require('superagent');

if (process.argv.length !== 3) {
    console.log('Usage: ./addUsers.js <cloudronDomain>');
    process.exit(1);
}

const cloudronDomain = process.argv[2];

function getAccessToken(callback) {
    let username = readlineSync.question('Username: ', {});
    let password = readlineSync.question('Password: ', { noEchoBack: true });

    superagent.post(`https://${cloudronDomain}/api/v1/developer/login`, { username: username, password: password }).end(function (error, result) {
        if (error || result.statusCode !== 200) {
            console.log('Login failed');
            return getAccessToken(callback);
        }

        callback(result.body.accessToken);
    });
}

console.log(`Login to ${cloudronDomain}`);
getAccessToken(function (accessToken) {
    console.log(`Now creating ${COUNT} users...`);

    async.timesLimit(COUNT, 5, function (n, next) {
        let user = {
            username: USERNAME_PREFIX + n,
            password: PASSOWRD_PREFIX + n,
            email: USERNAME_PREFIX + n + '@' + EMAIL_DOMAIN,
            displayName: DISPLAYNAME_PREFIX + n
        };

        superagent.post(`https://${cloudronDomain}/api/v1/users`, user).query({ access_token: accessToken }).end(function (error) {
            if (error) return next(error);

            process.stdout.write('.');

            next();
        });
    }, function (error) {
        console.log();

        if (error) {
            console.error(error);
            process.exit(1);
        }

        console.log('Done');
    });
});