#!/usr/local/Hughes/bin/lite

echo("Connecting to local mSQL server.\n");
$sock = msqlConnect("localhost");
if ($sock < 0) {
   fatal("Error: $ERRMSG");
   }

echo("Connected ... Selecting database CONTACTS.\n");
if (msqlSelectDB($sock,"contacts") < 0) {
   fatal("Error: $ERRMSG");
   }
echo("Done!\n\n");

echo("Please enter user name:\n");
$in=open("./newuser.input", "<|");
if ($in<0) { 
   echo("Error: $ERRMSG\n");
   exit(0);
   }
$user=chop(readln($in));
close($in);

echo("Please enter user pass:\n");
$in=open("./newuser.input", "<|");
if ($in<0) { 
   echo("Error: $ERRMSG\n");
   exit(0);
   }
$pass=chop(readln($in));
close($in);

echo("Please enter aditional data:\n");
$in=open("./newuser.input", "<|");
if ($in<0) { 
   echo("Error: $ERRMSG\n");
   exit(0);
   }
$data=chop(readln($in));
close($in);

if (msqlQuery($sock, "select * from all_accounts where user='$user'")<0) {
   fatal("Error: $ERRMSG");
   } 

$res=msqlStoreResult();
$row=msqlFetchRow($res);

if (#$row > 0) {
   echo("User '$user' already exist:\nData: $row[1]\n");
   exit(0);
}
msqlFreeResult($res);

if (msqlQuery($sock, "insert into all_accounts values ('$user','$data')")<0) {
   echo("Can not add user '$user' to database!\n");
   exit(0);
   } 
else {
   $nmn=$user + "_category";
   echo("User '$user' added to database succsessfuly\n");
   }

system("./chng $user | msql -h localhost contacts ");
system("/usr/local/Hughes/bin/msqlimport contacts $nmn < ./categories");

msqlClose($sock);
exit(0);

