#!/usr/bin/env perl

use strict;
use warnings;
use IO::Socket;
use Digest::MD5 qw(md5_hex);
BEGIN {
    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: $@";
};

main();

sub main {
    my $file = '/var/run/gt/gt.sock';
    die "Could not find $file\n" if ! -e $file;
    die "Should not run gt_user as root" if ! $<;
    my ($user, $pw, $uid, $gid, $q, $cmt, $g, $home) = getpwuid $<;
    die "Invalid user $user" if $user !~ /^[\w.-]+$/;
    die "User does not have a home" if ! $home || ! -d $home;

    my $sock = IO::Socket::UNIX->new(Peer => $file)
        || die "Could not connect to GT Socket: $!\n";

    my $w = eval { require Term::ReadKey } ? eval { local $SIG{'__WARN__'} = sub {}; (Term::ReadKey::GetTerminalSize())[0] } || 100
        : (-t STDIN) ? (`stty size 2>/dev/null` =~ /(\d+)$/ && $1) || 100
        : 100;

    my $priv;
    my $f = "$home/.gt_user";
    my ($mode, $u, $size) = (stat $f)[2, 4, 7];
    if (! $size || ($mode & 07777) != 0600) {
        open my $fh, '<', '/dev/urandom' or die "Could not get data from urandom: $!";
        20 == read $fh, my($b), 20 or die "Could not read bytes from urandom";
        $priv = unpack 'H*', $b;
        open $fh, '>', $f or die "Could not add data to $f: $!";
        print $fh $priv;
        chmod 0600, $f or die "Could not chmod 0600 $f: $!";
    } else {
        die "$f is not owned by $user" if $u != $uid;
        open my $fh, '<', $f or die "Could not open $f: $!";
        local $/;
        $priv = <$fh>;
    }

    my $json = encode_json({argv => \@ARGV});
    my $time = time;
    my $sum  = md5_hex($json);
    my $sig  = md5_hex(join '|', $user, $priv, $time, $sum);
    my $len  = length $json;
    print $sock <<"EOM" or die "Failed to send request: $!\n";
POST /gt_user/$user HTTP/1.0
Host: unixsock
X-gtu-auth: $sig:$time
X-gtu-width: $w
Content-length: $len
Content-type: application/json

$json
EOM

    my ($exit_code, $body);
    while (defined(my $line = <$sock>)) {
        if (! $body) {
            print $line if $ENV{'GT_USER_VERBOSE'};
            $exit_code = $1 if $line =~ /^X-cli-exit-code:\s+(\d+)/;
            $body = 1 if $line =~ /^\r?\n\z/;
            next;
        }
        print $line;
    }

    exit $exit_code if $exit_code;
}
