#!/usr/bin/perl
require '/usr/local/etc/httpd/cgi/parseform.pl';
require '/usr/local/etc/httpd/cgi/conv-lib2.pl';
$chardir = "/usr/local/etc/stuff";

# Spring, 1996, Matthew Gray <mkgray@mit.edu>

$pi = $ENV{'PATH_INFO'};
$qs = $ENV{'QUERY_STRING'};
$sn = $ENV{'SCRIPT_NAME'};
$svn = $ENV{'SERVER_NAME'};
$purl = "http://".$svn.$sn;

%form = &parseform($qs);
if($pi){
    ($user, $char) = split(/\//, substr($pi, 1));
    $form{'user'} = $user;
    $form{'char'} = $char;
}

#print("server $svn, script $sn, pi: $pi, User: $form{'user'}, Char: $form{'char'}\n");

if(!$qs &!$form{'user'})
{
    &loginScreen();
}
elsif($form{'user'} && $form{'newchar'})
{
    &characterCreation();
}
elsif($form{'user'} && !$form{'char'}){
    &characterSelection();
}
elsif($form{'user'} && $form{'char'} && !$form{'key'})
{
    if($form{'view'}){
	&viewChar();
    }
    else{
	if($form{'change'}){
	    &modifyChar();
	}
	else{
	    &keyList();
	}
    }
}
elsif($form{'user'} && $form{'char'} && $form{'key'} && !$form{'change'}){
    if($form{'delete'}){
	&deleteKey();
    }
    &editKey();
}
elsif($form{'user'} && $form{'char'} && $form{'key'} && $form{'change'}){
    &submitKey();
}

sub loginScreen {
    &html();
    print <<EndLoginScreen;
<h1>Using the Web Character Editor</h1>

This is a web interface to create files that can be used with the
Conversation program (aka MacConversation).
<p>

You will be asked to log in with a username.  At the moment, there is
no security in place, so someone who enters your username can edit
your characters.  For this reason, you may want to use some other
string as a username in this system rather than your standard athena
username.

<p>

In order to use the characters generated here, you will need to select
the "download character" option and then save the downloaded file on
your mahine.  Then, use a conversation program to interact with the
character.

<p>

Please notify <a href="mailto:mkgray@mit.edu">Matthew, mkgray@mit.edu</a> of any problems.

<hr>
<h1>Login to the Character Editor</h1>
<form>
Your Username: <input name="user">
</form>
EndLoginScreen
}

sub characterCreation {
    if($form{'charname'}){
	&createNew();
    }
    else{
	&createForm();
    }
}

sub createForm {
    &html();
    print <<EndCreateForm;
    <h1>Hello $form{'user'}</h1>
<h2>Character Creation</h2>
<form action=$purl/$user/>
<input type=hidden name=newchar value=1>
Create Character with name: <input name="charname">
</form> 
EndCreateForm
}
sub html {
    print("Content-type: text/html\n\n");
}
sub text {
    print("Content-type: text/plain\n\n");
}

sub createNew {
    &put(character,0,charname,$form{'charname'});
    &put(character,0,charauthor,$form{'user'});
    if(!-e "$chardir/$form{'user'}"){
	mkdir("$chardir/$form{'user'}",0777);
    }
    &writecharacter("$chardir/$form{'user'}/$form{'charname'}");
    $form{'char'} = $form{'charname'};
    &redirect("$purl/$form{'user'}/$form{'char'}");
}

sub characterSelection {
    if(!-e "$chardir/$form{'user'}"){
	mkdir("$chardir/$form{'user'}", 0777);
    }
    opendir(CDIR, "$chardir/$form{'user'}");
    @chars = readdir(CDIR);
    &html();
    print <<EndCharSel;
<h1>Select A Character to Edit</h1>
<hr>
<ol>
EndCharSel
    foreach $c (@chars){
	next if($c eq "." || $c eq "..");
	print("<li><a href=\"$purl/$form{'user'}/$c\">$c</a>\n");
    }
    print <<EndEndCharSel;
</ol>
<hr>
Or, you can <form action="$purl/$form{'user'}">
<input type=hidden name=newchar value=1>
<input type=submit value="Create a New Character">
</form>
EndEndCharSel
}

sub viewChar {
    &text;
    print `cat $chardir/$form{'user'}/$form{'char'}`;
}

sub modifyChar {
    &readcharacter("$chardir/$form{'user'}/$form{'char'}");
    &put(character,0,introline,$form{'introline'});
    &put(character,0,charstyle,$form{'charstyle'});
    &put(character,0,userstyle,$form{'userstyle'});
    &writecharacter("$chardir/$form{'user'}/$form{'char'}");
    &keyList();
}

sub submitKey {
    &readcharacter("$chardir/$form{'user'}/$form{'char'}");
    $key = $form{'key'};
    &put($key,0,randomize,$form{'randomize'}?"1":"0");
    @synonyms = split("\n", $form{'synonyms'});
    grep(s/[\n\r]//g, @synonyms);
    &put($key,0,synonyms,join("\t",($key, @synonyms)));
    $haveresps=1;
    $i = 0;
    while($haveresps){
	if($form{"response$i"} eq ""){
	    $haveresps = 0;
	}
	else{
	    &put($key,$i,response,$form{"response$i"});
	    &put($key,$i,repeatable,$form{"repeatable$i"}?"1":"0");
	    &put($key,$i,stayontopic,$form{"stayontopic$i"}?"1":"0");
	    &put($key,0,count,$i+1);
	    $i++;
	}
    }
    &writecharacter("$chardir/$form{'user'}/$form{'char'}");
    $ekey = $key;
    $ekey =~ s/([^a-zA-Z0-9])/"%".unpack("H2",$1)/eig;
    &redirect("$purl/$form{'user'}/$form{'char'}?key=$ekey");
}

sub deleteKey {
    &readcharacter("$chardir/$form{'user'}/$form{'char'}");
    delete $keysdata{$form{'key'}};
    &writecharacter("$chardir/$form{'user'}/$form{'char'}");
    &redirect("$purl/$form{'user'}/$form{'char'}");
}

sub editKey {
    &readcharacter("$chardir/$form{'user'}/$form{'char'}");
    $key = $form{'key'};
    $rand = &get($key,0,randomize);
    @synonyms = split("\t", &get($key,0,synonyms));
#    pop @synonyms;
    shift(@synonyms);
    $synonyms = join("\n", @synonyms);
    for $i (0..&get($key,0,count)-1){
	push(@responses, &get($key,$i,response));
	push(@repeatable, &get($key,$i,repeatable));
	push(@stayontopic, &get($key,$i,stayontopic));
    }
    $rcheck = "CHECKED" if $rand;
    &html();
    $ekey = $key;
    $ekey =~ s/([^a-zA-Z0-9])/"%".unpack("H2",$1)/eig;
    print <<EndKeyInfo;
<h1>Editing Key $key</h1>
<form action=$purl/$form{'user'}/$form{'char'}>
<input type=hidden name=change value=1>
<input type=hidden name=key value="$key">
Randomize?: <input type=checkbox name=randomize value=1 $rcheck>
<p>
Synonyms: (seperated by returns)<br>
<textarea rows=4 cols=35 name=synonyms>$synonyms</textarea>
<p>
<table>
<tr><th>Response</th><th>Repeatable?</th><th>Stay On Topic?</th></tr>
EndKeyInfo

    for $i (0..&get($key,0,count)+5){
	if(&get($key,$i,repeatable)) {
	    $rep = "CHECKED";
	}
	else{
	    $rep = "";
	}
	if(&get($key,$i,stayontopic)) {
	    $stay = "CHECKED";
	}
	else{
	    $stay = "";
	}
	print("<tr><td><input size=35 name=response$i value=\"$responses[$i]\"></td><td align=center><input type=checkbox name=repeatable$i value=1 $rep></td><td align=center><input type=checkbox name=stayontopic$i value=1 $stay></td></tr>\n");
    }
    print("</table><input type=submit value=\"Commit Changes\"></form>\n");
    $ekey = $key;
    $ekey =~ s/([^a-zA-Z0-9])/"%".unpack("H2",$1)/eig;
    print("<a href=\"$purl/$form{'user'}/$form{'char'}\">[Keyword List]</a> <a href=\"$purl/$form{'user'}/$form{'char'}?key=$ekey&delete=1\">[Delete this Key]</a>\n");
}

sub keyList {
    &readcharacter("$chardir/$form{'user'}/$form{'char'}");
    &html();
    $introline = &get(character, 0, introline);
    $charstyle = &get(character, 0, charstyle);
    $userstyle = &get(character, 0, userstyle);
    print <<EndKeyListHead;
    <h1>Greetings $form{'user'}</h1>
	<h2>Editing $form{'char'}</h2>
<hr>
<form action=$purl/$form{'user'}/$form{'char'}>
Intro Line: <input name=introline value="$introline">
<p>
Character Prompt: <input name=charstyle value="$charstyle">
<p>
User Prompt: <input name=userstyle value="$userstyle">
<p>
<input type=hidden name=change value=1>
<input type=submit value="Make Changes">
</form>
<hr>
<h2>Keywords</h2>
<ol>
EndKeyListHead

    foreach $k (sort keys %keysdata){
	next if $k eq "character";
	$complete =1 if $k eq "@DUMMY@";
	$esck = $k;
	$esck =~ s/([^a-zA-Z0-9])/"%".unpack("H2",$1)/eig;

	print("<li><a href=\"$purl/$form{'user'}/$form{'char'}?key=$esck\">$k</a>\n");
    }
    print("</ol>\n");
    if (!$complete) {
	print("<strong>Warning!</strong> This character does not have a '@DUMMY@' response to use as a default.  You should <a href=$purl/$form{'user'}/$form{'char'}?key=@DUMMY@>create one now</a>.\n");
    }
    print <<EndKeyListFoot;
<form action=http://$svn$sn/$form{'user'}/$form{'char'}>
Create New Keyword: <input name=key>
</form>
<a href="$purl/$form{'user'}">[List of Characters]</a> 
<a href="$purl/$form{'user'}/$form{'char'}?view=1">[Download this Character]</a>
EndKeyListFoot
}


sub redirect {
    local($where) = @_;
    
    print("Location: $where\n\n");
}
