#!/usr/bin/perl

use strict;
use warnings;

use IPC::Open2;
use Fcntl qw(F_SETFL F_GETFL O_NONBLOCK);

my ($rh, $wh);
my $pid = open2 ($rh, $wh, "gcloud auth login --no-launch-browser") or die "gcloud auth loing failed: $!";

my $flags = fcntl ($rh, F_GETFL, 0) or die "can't get flags: $!";
fcntl ($rh, F_SETFL, $flags|O_NONBLOCK) or die "can't set O_NONBLOCK: 
+$!";

#print $wh "ls foo\n";

my $ln;

while (! ($ln = <$rh>)) {}    ## wait for valid output

print "Enter Google auth response code:\n";
my $google_auth_response_code = <STDIN>;
#chomp $google_auth_response_code;

print "Writing response code to gcloud auth login open2() pipe\n";

print $wh $google_auth_response_code;

print "sent\n";

print "Waiting on $pid\n";    

waitpid $pid, 0;
