#!/usr/bin/env node

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

// WARNING keep those in sync with addUsers.js
const USERNAME_PREFIX = 'manyuser';

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

if (process.argv.length !== 3) {
    console.log('Usage: ./delUsers.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('Listing users...');

    superagent.get(`https://${cloudronDomain}/api/v1/users`).query({ access_token: accessToken, per_page: 1000 }).end(function (error, result) {
            if (error) {
                console.error(error);
                process.exit(1);
            }

            console.log(`Found ${result.body.users.length} users`);
            let matchingUsers = result.body.users.filter(function (u) { return u.username.indexOf(USERNAME_PREFIX) === 0; });
            console.log(`Found ${matchingUsers.length} users with matching prefix`);

            console.log('Deleting users...');

            async.eachLimit(matchingUsers, 5, function (user, next) {
                superagent.del(`https://${cloudronDomain}/api/v1/users/${user.id}`).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');
            });
        });

});