<?php

/**
 * Purge users from the system who have not logged in
 * in the last X days (where X is passed as an argument)
 * to this script
 * 
 * @author Brad Kowalczyk <brad@staff.atmail.com>
 * @usage php purge-users.php [days-inactive] [--no-delete] [--read-user-list]
 */

require_once(dirname(dirname(__FILE__)) . "/nfc-bootloader.php");

// require that the argument is numeric
if (!in_array("--read-user-list", $_SERVER['argv']) && !is_numeric($_SERVER['argv'][1])) {
	echo "\nUsage: php purge-users.php [days-inactive] [--no-delete] [--read-user-list]\n\n".
	     "days-inactive\tDelete users inactive for this many days or more\n".
	     "--no-delete\tdo not actually delete any users, just print them\n".
         "--read-user-list\tRead a list of users to delete from STDIN, format should be one user per line. days-inactive is ignored\n\n";
	exit;
}

$delete = (!in_array("--no-delete", $_SERVER['argv']));

// setup api access
require_once('application/models/api.php');
$_SERVER['PHP_AUTH_USER'] = (isset($_SERVER['argv'][2]))? $_SERVER['argv'][2] : 'admin';
$api = new api( array('directApi' => 1) );

if (!$delete) {
	fwrite(STDOUT, "TEST RUN -- no accounts actually deleted\n");
}

if (in_array("--read-user-list", $_SERVER['argv'])) {
    while(false !== $user = fgets(STDIN)) {
        $user = trim($user);
        if (empty($user)) {
            continue;
        }

        fwrite(STDOUT, "Deleting $user...");
        if ($delete) {
            try {
                $res = $api->userDelete($user);
                if ($res['status'] == 'failed') {
                    fwrite(STDOUT, " FAILED: {$res['response']['message']}\n");
                } else {
                    fwrite(STDOUT, " OK\n");
                }
            } catch (Exception $e) {
                fwrite(STDOUT, " FAILED: " . $e->getMessage() . "\n");
            }
        }
    }

    exit;
}

// make doubly sure that only digits are in the days-inactive argument
$days = preg_replace("/[^0-9]/", "", $_SERVER['argv'][1]);

// fetch our list of inactive accounts
$res = $dbAdapter->query("SELECT LastLogin.* FROM Users left join (SELECT Account, max(LogDate) AS LastLogin FROM Log_Login group by Account) LastLogin on Users.Account = LastLogin.Account where LastLogin < date_sub(NOW(), interval $days day)");

while ($row = $res->fetch()) {

	fwrite(STDOUT, "Deleting {$row['Account']}, inactive since {$row['LastLogin']}\n");
	if ($delete) {
        try {
            $res = $api->userDelete($row['Account']);
            if ($res['status'] == 'failed') {
                fwrite(STDOUT, " FAILED: {$res['response']['message']}\n");
            } else {
                fwrite(STDOUT, " OK\n");
            }
        } catch (Exception $e) {
            fwrite(STDOUT, " FAILED: " . $e->getMessage() . "\n");
        }
	}
}
