#!/usr/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/$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");

# Извлечь номер дисплея из session ID (user-52-1747..._stDMATE_dp24 → 52)
my ($display_num) = $X2GO_SESSION_ID =~ /^[^-]+-(\d+)-/;
my $socket_path = $ENV{HOME}."/.x2go/$X2GO_SESSION_ID-pcscd.comm";

# UID пользователя для systemd user bus
my $uid = `id -u $cuser`;
chomp $uid;

# Подождать пока сокет появится (ssh -f создаёт его асинхронно)
my $wait = 0;
while ( ! -S $socket_path && $wait < 10 ) {
    sleep(1);
    $wait++;
}

# Пробросить переменную в окружение запущенной X-сессии
my $dbus = "unix:path=/run/user/$uid/bus";
system("DISPLAY=:$display_num DBUS_SESSION_BUS_ADDRESS=$dbus " .
       "dbus-update-activation-environment --systemd " .
       "PCSCLITE_CSOCK_NAME=$socket_path 2>/dev/null");

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

