#!/afs/athena/contrib/perl5/perl

$readline::rl_completion_function = "main::complete";
$prompt = "% ";

use Term::ReadLine;

@path = split(":", $ENV{'PATH'});
$term = new Term::ReadLine 'kosh';
print("And so it begins.\n");
while(1){
    $inp = $term->readline("$prompt");
    if(substr($inp, 0, 2) eq ": "){
	eval(substr($inp, 2));
    }
    elsif(&kosh($inp)){
    }
    elsif(&internal_cmd($inp)){
	}
    elsif(!&trytoexec($inp)){
	print("What is need compared to the path?\n");
    }
}

sub kosh  {
	my($c) = (@_);
	($cmd, @opts) = split(" ", $c);

	%resps = ( "su", "You are not yet ready to become root.",
		   "xpaint", "A stroke of the brush does not guarantee art from the bristles",
		"file", "$opts[0]: Reflection, surprise, terror. For the future",
		"what", "Never ask that question",
		"where", "Never ask that question",
		"which", "Never ask that question",
		"who", "Never ask that question",
		"yes", "Yes.");

	foreach $k (keys %resps){
		if($cmd eq $k){
			print($resps{$k}, "\n");
			return 1;
		}
	}

	if($cmd eq "pwd"){
		print("You have always been here...\n");
		return 0;
	}
	elsif(($cmd eq "more") && ($opts[0] eq "/var/adm/messages")){
		print("They are not for you.\n");
		return 1;
	}
	elsif($cmd eq "yes"){
		print("Yes.\n");
		return 1;
	}
	return 0;
}

sub internal_cmd {
	my($c) = (@_);
	($cmd, @opts) = split(" ", $c);
	if($cmd eq "cd"){
		if($opts[0]){	
			chdir($opts[0]);
		}
		else{
			chdir($ENV{'HOME'});
		}
		return 1;
	}
	if($cmd eq "exit"){
		exit;
	}
}

sub complete {
    my($t, $a, $s) = @_;
    "$t";
}

sub trytoexec {
    my(@cmd) = @_;

    foreach $p (@path){
	if(-e "$p/$cmc[0]"){
	    if(fork()) {
		wait;
		return 1;
	    }
	    else {
		exec(@cmd);
		exit;
	    }
	}
    }
}
