#!/usr/bin/perl -w
use strict;
use IO::Socket;
use IO::Socket::INET6;

my ($host, $port, $kidpid, $remote, $line, $file, $file2, $datafile);
unless (@ARGV == 3) { die "client: usage: \n$0 host port datafile \n" }
($host, $port, $datafile) = @ARGV;

$file="$datafile.tsq";
print "client: tsq file: $file \n";
$file2="$datafile.tsr";
print "client: tsr file: $file2 \n";

#print "client: ",`openssl ts -query -sha512 -no_nonce -data $datafile -out $file`;
print "client: ",`openssl ts -query -sha512 -no_nonce -cert -data $datafile -out $file`;

$remote = IO::Socket::INET6->new(Proto     => "tcp",
                                PeerAddr  => $host,
                                PeerPort  => $port)
               or die "client: can't connect to port $port on $host: $!\n";

$remote->autoflush(1);
print STDERR "client: [Connected to $host:$port]\n";
die "client: can't fork: $!\n" unless defined($kidpid = fork());

sub screen {
    while (defined($_=<$remote>)) {
    print STDOUT $_;
    kill("TERM", $kidpid);  # send SIGTERM to child
    }
}

if ($kidpid) {
    # from socket to output
    my ($buff,$rozmiar,$x,$l1,$l2,$i);
    recv($remote,$buff,1,0);
    open(WYJ,">$file2");
    print WYJ $buff;
    close(WYJ);

    recv($remote,$buff,1,0);
    open(WYJ,">>$file2");
    print WYJ $buff;
    $x = unpack("H*",$buff);
    $l1 = hex($x);

    if(hex($x) > hex(80)){

    recv($remote,$buff,2,0);
    print WYJ $buff;
    $x = unpack("H*",$buff);
    $l2 = hex($x);
        for($i=$l2;$i>0;$i--){
        recv($remote,$buff,1,0);
        print WYJ $buff;
        }
    }
    else{
    recv($remote,$buff,$l1,0);
    print WYJ $buff;
    }
close WYJ;

    if( -T $file2){
    print "error message: \n";
    open(WYJ,"$file2");
        while(<WYJ>){
        print $_, "\n";
        }
    close WYJ;
    `rm -f $file2`;
    }
}
else {
    open(WEJ, "$file");
    binmode WEJ;
    while (<WEJ>) {
        print $remote $_;
    }
    close WEJ;
    $remote->shutdown(1) or die "client: shutdown: $!\n";
    print "client: transfer of the $file to the server completed \n";
    print "client: ", `du -b $file`;
}
