#!/usr/bin/php
<?php

// '{SHA}' . base64_encode(sha1($password, TRUE))

if ($argc != 4) {
	fwrite(STDERR, "Syntax: passwdfile username password\n");
	exit(2);
}

$passwdfile  = $argv[1];
$username    = $argv[2];
$newPassword = $argv[3];

if (!file_exists($passwdfile)) {
	fwrite(STDERR, "File $passwdfile not found\n");
	exit(1);
}

$out = array();

$lines = file($passwdfile);
foreach ($lines as $line) {
	$line = trim($line);
	$ary = explode(':', $line);
	if ((count($ary) == 2) && ($ary[0] == $username)) {
		$out[] = $username.':'.'{SHA}'.base64_encode(sha1($newPassword, TRUE));
	} else {
		$out[] = $line;
	}
}

file_put_contents($passwdfile, trim(implode("\n", $out))."\n");
