#!/usr/bin/env perl

use strict;
use warnings;
use IO::Socket;

main();

sub main {
    eval { require Cpanel::JSON::XS; import Cpanel::JSON::XS qw(encode_json); 1 }
        || eval { require JSON::XS; import JSON::XS qw(encode_json); 1 }
        || eval { require JSON; import JSON qw(encode_json); 1 }
        || die "Could not load json: $@";

    my $file = $ENV{'GT_USER_SOCK'} || '/var/run/gt/gt_user.sock';
    die "It does not appear that gt_server is running.  Could not find gt_user file $file\n" if ! -e $file;

    my $width = eval { require Term::ReadKey } ? eval { local $SIG{'__WARN__'} = sub {}; (Term::ReadKey::GetTerminalSize())[0] }
        : (-t STDIN) ? (`stty size 2>/dev/null` =~ /(\d+)$/ && $1) : 0;
    my $json = encode_json({width => $width, argv => \@ARGV, time => time()});

    my $sock = IO::Socket::UNIX->new(Peer => $file) || die "Could not connect to gt_user file $file: $!\n";
    my $id = $<;
    $id .= ":$ENV{'GT_USER_UID'}" if $ENV{'GT_USER_UID'};
    print $sock "$id\n$json\n";

    chomp(my $exit_code = <$sock> // die "Failed calling gt_user\n");

    if ($exit_code eq 'sig') {
        require Digest::SHA;
        chomp(my $file = <$sock>);
        die "Could not get gt_user token\n" if ! $file || ! open my $fh, '<', $file;
        my $tok = do { local $/; <$fh> } || die "Could not read gt_user token\n";
        print $sock Digest::SHA::sha256_hex($tok.$json)."\n";
        chomp($exit_code = <$sock> // die "Failed calling gt_user\n");
    }

    print <$sock>;
    exit $exit_code if $exit_code;
}
