#!/bin/perl
my $cuser=shift;
my $key=shift;
my $direction=shift;
my $port=shift;
my $sock=shift;
my $X2GO_SESSION_ID=shift;

my $host;

if ($direction eq "dir") { $host=(split(" ",$ENV{'SSH_CLIENT'}))[0]; }
elsif ($direction eq "rev") { $host="127.0.0.1"; }
else { exit(1); }

open (F, "<$key");
my @lines=<F>;

my $lines=join("",@lines);
my ($dsa_key,$rsa_identity) = split("----BEGIN RSA IDENTITY----",$lines);
open (F, ">$key.ident");
printf F "\[$host\]:$port $rsa_identity";
close(F);

printf $direction;


chmod(0600,"$key.ident");
chmod(0600,$key);

system("ssh -f -N -i $key -oStreamLocalBindUnlink=yes -oUserKnownHostsFile=$key.ident -L ~/.x2go/C-$X2GO_SESSION_ID/$X2GO_SESSION_ID-pcscd.comm:$sock -p $port $cuser\@$host &>/dev/null");
system("pgrep -f \"ssh.*$key.*pcscd.*\" > ~/.x2go/C-$X2GO_SESSION_ID/ssh_scard.pid");

unlink("$key.ident");
unlink($key);
exit(0);