#!/usr/bin/php
<?php
$argv=$_SERVER[argv];
if($argv[3]=='')
die("Usage: $argv[0] passwordfile realm username [password]\r\n");
if($argv[4]=='') {
	$fp=fopen('php://stdin','r'); 
	$argv[4]=fgets($fp);
	fclose($fp);
}

htdigest($argv[3],$argv[4],$argv[2],$argv[1]);


#//浠f浛apache2鐨勫瘑鐮佺▼搴廻tdigest
function htdigest($username,$password,$realm='bjlx.org.cn',$passwordfile='/etc/apache2/user.passwd') {
	if(!file_exists($passwordfile)) {
		file_put_contents($passwordfile,'');
		chmod($passwordfile,0666);
	}
	if(!file_exists($passwordfile)) return;
	$fp=fopen($passwordfile,'r+');
	if(!$fp) return;
	$pass="$username:$realm:".md5("$username:$realm:$password");
	if(flock($fp,LOCK_EX)) {
		while(!feof($fp)) {
			$line=trim(fgets($fp));
			$a=explode(':',$line);
                        if($a[1]=='') continue;
			if($a[0]==$username && $a[1]==$realm){
				if($pass!='') {
					$str1.=$pass."\n";
					$pass='';
				}
			}else		
				$str.=$line."\n";
		}
		$str.=$str1;

		if($pass!='') $str.=$pass;
		$str=trim($str);
		fseek($fp,0);
		$flen=strlen($str);
		fwrite($fp,$str,$flen);
		ftruncate($fp,$flen);
		flock($fp,LOCK_UN);
	}
	fclose($fp);
}