#!/usr/bin/php
<?php
	chdir(__DIR__);
	require("../libraries/banshee.php");
	require("../libraries/security.php");

	error_reporting(E_ALL & ~E_NOTICE);

	$db = new MySQLi_connection(DB_HOSTNAME, DB_DATABASE, DB_USERNAME, DB_PASSWORD);
	if ($db->connected == false) {
		exit("Internal error: database not available.\n");
	}

	if (count($argv) <= 1) {
		exit("Usage: ".$argv[0]." <username> [-t(test)]\n");
	}
	$username = $argv[1];
	$test = ($argv[2] === "-t");

	/* Check username
	 */
	if ($test == false) {
		$query = "select count(*) as count from users where username=%s";
		if (($result = $db->execute($query, $username)) === false) {
			exit("Error while checking username.\n");
		}
		if ($result[0]["count"] == 0) {
			exit("User ".$username." not found.\n");
		}
	}

	do {
		print "Enter password: ";
		system("/bin/stty -echo");
		$password = trim(fgets(STDIN));
		system("/bin/stty echo");
		print "\n";
	} while ($password == "");

	$password = hash_password($password, $username);

	if ($test == false) {
		$query = "update users set password=%s where username=%s";
		if ($db->query($query, $password, $username) === false) {
			exit("Database error while setting password.\n");
		}
	} else {
		printf("Password: %s\n", $password);
	}
?>
