#!/usr/bin/perl  -w

require 5.002;
use Socket;
use Unicode::Utf7;
use Getopt::Std;


# Init and globals

my $proto = getprotobyname('tcp');
my $port = getservbyname('saft', 'tcp');
my $CRLF = "\x0d\x0a";

my $host;
my $user;
my $message;

my $whoami = $ENV{'USER'} . ' ' . isotoutf7((getpwnam($ENV{'USER'}))[6]);


getopts('h:u:m:');

$host = !defined($opt_h) ? 'localhost' : $opt_h;

if(!defined($opt_u)) {
    print <<"EOT";
MISSING username!

USAGE: psendmsg.pl [-h host] -u user
EOT
    exit 1;
} else {
    $user = $opt_u;
}


if(defined($opt_m)) {
    $message = $opt_m;
} else {
    my $line;
    $message = '';
    
    print "Enter your message, terminated with single '.':\n\n--->\n";
    
    $line = <STDIN>;
    
    while($line !~ /^\.$/) {
        $message = $message . $line;
        $line = <STDIN>;
    }
    print "<---\n\n";
}

my $hisiaddr = inet_aton($host)     || die "unknown host";
my $hispaddr = sockaddr_in($port, $hisiaddr);
socket(SOCKET, PF_INET, SOCK_STREAM, $proto)   || die "socket: $!";
connect(SOCKET, $hispaddr)          || die "bind: $!";

select(SOCKET); $|=1; select(STDOUT);

print SOCKET "from $whoami$CRLF";
print SOCKET "to ", isotoutf7($user),$CRLF;
print SOCKET "msg ", isotoutf7($message), $CRLF;
print SOCKET "quit",$CRLF;
while(<SOCKET>) {
    print;
}
close(SOCKET);
